From c9c4b6f32d812a59186f79ef6d2564e173081f7c Mon Sep 17 00:00:00 2001 From: Kyle Thompson Date: Mon, 8 Nov 2021 11:51:50 -0500 Subject: [PATCH 1/2] Support exact-matching on FormData bodies --- package.json | 1 + src/Route/matchers.js | 2 +- test/specs/routing/body-matching.test.js | 68 +++++++++++++++++++++++- 3 files changed, 69 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 95d4b213..21dc0ee8 100644 --- a/package.json +++ b/package.json @@ -72,6 +72,7 @@ "eslint-config-origami-component": "1.0.0", "eslint-config-prettier": "^2.9.0", "eslint-plugin-prettier": "^2.6.1", + "form-data": "^2.3.3", "karma": "^3.1.4", "karma-chai": "^0.1.0", "karma-chrome-launcher": "^2.2.0", diff --git a/src/Route/matchers.js b/src/Route/matchers.js index c53049fa..bf707efe 100644 --- a/src/Route/matchers.js +++ b/src/Route/matchers.js @@ -142,7 +142,7 @@ const getBodyMatcher = (route, fetchMock) => { return true; } - let sentBody; + let sentBody = body; try { debug(' Parsing request body as JSON'); diff --git a/test/specs/routing/body-matching.test.js b/test/specs/routing/body-matching.test.js index c5ef3c98..40859780 100644 --- a/test/specs/routing/body-matching.test.js +++ b/test/specs/routing/body-matching.test.js @@ -1,3 +1,4 @@ +const FormData = require('form-data'); const chai = require('chai'); const expect = chai.expect; @@ -64,7 +65,7 @@ describe('body matching', () => { expect(fm.calls(true).length).to.equal(0); }); - it('should not match if body sent isn’t JSON', async () => { + it('should not match if the bodies are of different types', async () => { fm.mock({ body: { foo: 'bar' } }, 200).catch(); await fm.fetchHandler('http://a.com/', { @@ -112,6 +113,54 @@ describe('body matching', () => { expect(fm.calls(true).length).to.equal(1); }); + it('should match exact FormData bodies', async () => { + const formData = new FormData(); + formData.append('foo', 'bar'); + + fm.mock({ body: formData }, 200).catch(); + + await fm.fetchHandler('http://a.com/', { + method: 'POST', + body: formData, + headers: {}, + }); + expect(fm.calls(true).length).to.equal(1); + }); + + it('should not match FormData bodies that are not the same', async () => { + const expectedFormData = new FormData(); + expectedFormData.append('foo', 'bar'); + + fm.mock({ body: expectedFormData }, 200).catch(); + + const actualFormData = new FormData(); + actualFormData.append('fizz', 'buzz'); + await fm.fetchHandler('http://a.com/', { + method: 'POST', + body: actualFormData, + headers: {}, + }); + expect(fm.calls(true).length).to.equal(0); + }); + + it('should not ignore the order of the form fields', async () => { + const expectedFormData = new FormData(); + expectedFormData.append('foo', 'bar'); + expectedFormData.append('fizz', 'buzz'); + + fm.mock({ body: expectedFormData }, 200).catch(); + + const actualFormData = new FormData(); + actualFormData.append('fizz', 'buzz'); + actualFormData.append('foo', 'bar'); + await fm.fetchHandler('http://a.com/', { + method: 'POST', + body: actualFormData, + headers: {}, + }); + expect(fm.calls(true).length).to.equal(0); + }); + describe('partial body matching', () => { it('match when missing properties', async () => { fm.mock({ body: { ham: 'sandwich' }, matchPartialBody: true }, 200).catch( @@ -170,5 +219,22 @@ describe('body matching', () => { }); expect(res.status).to.equal(404); }); + + it('should not support partial matches of FormData bodies', async () => { + const expectedFormData = new FormData(); + expectedFormData.append('foo', 'bar'); + + fm.mock({ body: expectedFormData, matchPartialBody: true }, 200).catch(); + + const actualFormData = new FormData(); + actualFormData.append('fizz', 'buzz'); + actualFormData.append('foo', 'bar'); + await fm.fetchHandler('http://a.com/', { + method: 'POST', + body: actualFormData, + headers: {}, + }); + expect(fm.calls(true).length).to.equal(0); + }); }); }); From 25db1d5469be4046dbaefef7ab2d4ceb1038e908 Mon Sep 17 00:00:00 2001 From: Kyle Thompson Date: Mon, 8 Nov 2021 14:41:01 -0500 Subject: [PATCH 2/2] Commit built files (to avoid necessity of an NPM publish) --- .gitignore | 6 +- cjs/Route/index.js | 150 + cjs/Route/matchers.js | 238 + cjs/client-legacy.js | 5 + cjs/client.js | 17 + cjs/lib/debug.js | 29 + cjs/lib/fetch-handler.js | 309 + cjs/lib/index.js | 75 + cjs/lib/inspecting.js | 215 + cjs/lib/request-utils.js | 135 + cjs/lib/response-builder.js | 197 + cjs/lib/set-up-and-tear-down.js | 150 + cjs/lib/status-text.js | 66 + cjs/package.json | 1 + cjs/server.js | 32 + es5/Route/index.js | 206 + es5/Route/matchers.js | 306 + es5/client-bundle.js | 6559 +++ es5/client-legacy-bundle.js | 79513 ++++++++++++++++++++++++++++++ es5/client-legacy.js | 7 + es5/client.js | 21 + es5/lib/debug.js | 33 + es5/lib/fetch-handler.js | 482 + es5/lib/index.js | 84 + es5/lib/inspecting.js | 278 + es5/lib/request-utils.js | 171 + es5/lib/response-builder.js | 209 + es5/lib/set-up-and-tear-down.js | 172 + es5/lib/status-text.js | 67 + es5/server.js | 39 + esm/client.d.ts | 697 + esm/client.js | 4825 ++ esm/package.json | 1 + esm/server.d.ts | 697 + esm/server.js | 26186 ++++++++++ 35 files changed, 122175 insertions(+), 3 deletions(-) create mode 100644 cjs/Route/index.js create mode 100644 cjs/Route/matchers.js create mode 100644 cjs/client-legacy.js create mode 100644 cjs/client.js create mode 100644 cjs/lib/debug.js create mode 100755 cjs/lib/fetch-handler.js create mode 100644 cjs/lib/index.js create mode 100644 cjs/lib/inspecting.js create mode 100644 cjs/lib/request-utils.js create mode 100644 cjs/lib/response-builder.js create mode 100644 cjs/lib/set-up-and-tear-down.js create mode 100644 cjs/lib/status-text.js create mode 100644 cjs/package.json create mode 100644 cjs/server.js create mode 100644 es5/Route/index.js create mode 100644 es5/Route/matchers.js create mode 100644 es5/client-bundle.js create mode 100644 es5/client-legacy-bundle.js create mode 100644 es5/client-legacy.js create mode 100644 es5/client.js create mode 100644 es5/lib/debug.js create mode 100755 es5/lib/fetch-handler.js create mode 100644 es5/lib/index.js create mode 100644 es5/lib/inspecting.js create mode 100644 es5/lib/request-utils.js create mode 100644 es5/lib/response-builder.js create mode 100644 es5/lib/set-up-and-tear-down.js create mode 100644 es5/lib/status-text.js create mode 100644 es5/server.js create mode 100644 esm/client.d.ts create mode 100644 esm/client.js create mode 100644 esm/package.json create mode 100644 esm/server.d.ts create mode 100644 esm/server.js diff --git a/.gitignore b/.gitignore index 381d0a75..626aedca 100644 --- a/.gitignore +++ b/.gitignore @@ -11,7 +11,7 @@ coverage/ .nyc_output # built files -/es5 -/esm -/cjs +# /es5 +# /esm +# /cjs /docs/_site/ diff --git a/cjs/Route/index.js b/cjs/Route/index.js new file mode 100644 index 00000000..c5191350 --- /dev/null +++ b/cjs/Route/index.js @@ -0,0 +1,150 @@ +const builtInMatchers = require('./matchers'); + +const { debug, setDebugNamespace, getDebug } = require('../lib/debug'); + +const isUrlMatcher = (matcher) => + matcher instanceof RegExp || + typeof matcher === 'string' || + (typeof matcher === 'object' && 'href' in matcher); + +const isFunctionMatcher = (matcher) => typeof matcher === 'function'; + +class Route { + constructor(args, fetchMock) { + this.fetchMock = fetchMock; + const debug = getDebug('compileRoute()'); + debug('Compiling route'); + this.init(args); + this.sanitize(); + this.validate(); + this.generateMatcher(); + this.limit(); + this.delayResponse(); + } + + validate() { + if (!('response' in this)) { + throw new Error('fetch-mock: Each route must define a response'); + } + + if (!Route.registeredMatchers.some(({ name }) => name in this)) { + throw new Error( + "fetch-mock: Each route must specify some criteria for matching calls to fetch. To match all calls use '*'" + ); + } + } + + init(args) { + const [matcher, response, options = {}] = args; + + const routeConfig = {}; + + if (isUrlMatcher(matcher) || isFunctionMatcher(matcher)) { + routeConfig.matcher = matcher; + } else { + Object.assign(routeConfig, matcher); + } + + if (typeof response !== 'undefined') { + routeConfig.response = response; + } + + Object.assign(routeConfig, options); + Object.assign(this, routeConfig); + } + + sanitize() { + const debug = getDebug('sanitize()'); + debug('Sanitizing route properties'); + + if (this.method) { + debug(`Converting method ${this.method} to lower case`); + this.method = this.method.toLowerCase(); + } + if (isUrlMatcher(this.matcher)) { + debug('Mock uses a url matcher', this.matcher); + this.url = this.matcher; + delete this.matcher; + } + + this.functionMatcher = this.matcher || this.functionMatcher; + + debug('Setting route.identifier...'); + debug(` route.name is ${this.name}`); + debug(` route.url is ${this.url}`); + debug(` route.functionMatcher is ${this.functionMatcher}`); + this.identifier = this.name || this.url || this.functionMatcher; + debug(` -> route.identifier set to ${this.identifier}`); + } + + generateMatcher() { + setDebugNamespace('generateMatcher()'); + debug('Compiling matcher for route'); + + const activeMatchers = Route.registeredMatchers + .map( + ({ name, matcher, usesBody }) => + this[name] && { matcher: matcher(this, this.fetchMock), usesBody } + ) + .filter((matcher) => Boolean(matcher)); + + this.usesBody = activeMatchers.some(({ usesBody }) => usesBody); + + debug('Compiled matcher for route'); + setDebugNamespace(); + this.matcher = (url, options = {}, request) => + activeMatchers.every(({ matcher }) => matcher(url, options, request)); + } + + limit() { + const debug = getDebug('limit()'); + debug('Limiting number of requests to handle by route'); + if (!this.repeat) { + debug( + ' No `repeat` value set on route. Will match any number of requests' + ); + return; + } + + debug(` Route set to repeat ${this.repeat} times`); + const matcher = this.matcher; + let timesLeft = this.repeat; + this.matcher = (url, options) => { + const match = timesLeft && matcher(url, options); + if (match) { + timesLeft--; + return true; + } + }; + this.reset = () => (timesLeft = this.repeat); + } + + delayResponse() { + const debug = getDebug('delayResponse()'); + debug(`Applying response delay settings`); + if (this.delay) { + debug(` Wrapping response in delay of ${this.delay} miliseconds`); + const response = this.response; + this.response = () => { + debug(`Delaying response by ${this.delay} miliseconds`); + return new Promise((res) => + setTimeout(() => res(response), this.delay) + ); + }; + } else { + debug( + ` No delay set on route. Will respond 'immediately' (but asynchronously)` + ); + } + } + + static addMatcher(matcher) { + Route.registeredMatchers.push(matcher); + } +} + +Route.registeredMatchers = []; + +builtInMatchers.forEach(Route.addMatcher); + +module.exports = Route; diff --git a/cjs/Route/matchers.js b/cjs/Route/matchers.js new file mode 100644 index 00000000..bf707efe --- /dev/null +++ b/cjs/Route/matchers.js @@ -0,0 +1,238 @@ +const { debug } = require('../lib/debug'); +const glob = require('glob-to-regexp'); +const pathToRegexp = require('path-to-regexp'); +const querystring = require('querystring'); +const isSubset = require('is-subset'); +const { + headers: headerUtils, + getPath, + getQuery, + normalizeUrl, +} = require('../lib/request-utils'); +const isEqual = require('lodash.isequal'); + +const debuggableUrlFunc = (func) => (url) => { + debug('Actual url:', url); + return func(url); +}; + +const stringMatchers = { + begin: (targetString) => + debuggableUrlFunc((url) => url.indexOf(targetString) === 0), + end: (targetString) => + debuggableUrlFunc( + (url) => url.substr(-targetString.length) === targetString + ), + glob: (targetString) => { + const urlRX = glob(targetString); + return debuggableUrlFunc((url) => urlRX.test(url)); + }, + express: (targetString) => { + const urlRX = pathToRegexp(targetString); + return debuggableUrlFunc((url) => urlRX.test(getPath(url))); + }, + path: (targetString) => + debuggableUrlFunc((url) => getPath(url) === targetString), +}; + +const getHeaderMatcher = ({ headers: expectedHeaders }) => { + debug('Generating header matcher'); + if (!expectedHeaders) { + debug(' No header expectations defined - skipping'); + return; + } + const expectation = headerUtils.toLowerCase(expectedHeaders); + debug(' Expected headers:', expectation); + return (url, { headers = {} }) => { + debug('Attempting to match headers'); + const lowerCaseHeaders = headerUtils.toLowerCase( + headerUtils.normalize(headers) + ); + debug(' Expected headers:', expectation); + debug(' Actual headers:', lowerCaseHeaders); + return Object.keys(expectation).every((headerName) => + headerUtils.equal(lowerCaseHeaders[headerName], expectation[headerName]) + ); + }; +}; + +const getMethodMatcher = ({ method: expectedMethod }) => { + debug('Generating method matcher'); + if (!expectedMethod) { + debug(' No method expectations defined - skipping'); + return; + } + debug(' Expected method:', expectedMethod); + return (url, { method }) => { + debug('Attempting to match method'); + const actualMethod = method ? method.toLowerCase() : 'get'; + debug(' Expected method:', expectedMethod); + debug(' Actual method:', actualMethod); + return expectedMethod === actualMethod; + }; +}; + +const getQueryStringMatcher = ({ query: passedQuery }) => { + debug('Generating query parameters matcher'); + if (!passedQuery) { + debug(' No query parameters expectations defined - skipping'); + return; + } + const expectedQuery = querystring.parse(querystring.stringify(passedQuery)); + debug(' Expected query parameters:', passedQuery); + const keys = Object.keys(expectedQuery); + return (url) => { + debug('Attempting to match query parameters'); + const query = querystring.parse(getQuery(url)); + debug(' Expected query parameters:', expectedQuery); + debug(' Actual query parameters:', query); + return keys.every((key) => { + if (Array.isArray(query[key])) { + if (!Array.isArray(expectedQuery[key])) { + return false; + } else { + return isEqual(query[key].sort(), expectedQuery[key].sort()); + } + } + return query[key] === expectedQuery[key]; + }); + }; +}; + +const getParamsMatcher = ({ params: expectedParams, url: matcherUrl }) => { + debug('Generating path parameters matcher'); + if (!expectedParams) { + debug(' No path parameters expectations defined - skipping'); + return; + } + if (!/express:/.test(matcherUrl)) { + throw new Error( + 'fetch-mock: matching on params is only possible when using an express: matcher' + ); + } + debug(' Expected path parameters:', expectedParams); + const expectedKeys = Object.keys(expectedParams); + const keys = []; + const re = pathToRegexp(matcherUrl.replace(/^express:/, ''), keys); + return (url) => { + debug('Attempting to match path parameters'); + const vals = re.exec(getPath(url)) || []; + vals.shift(); + const params = keys.reduce( + (map, { name }, i) => + vals[i] ? Object.assign(map, { [name]: vals[i] }) : map, + {} + ); + debug(' Expected path parameters:', expectedParams); + debug(' Actual path parameters:', params); + return expectedKeys.every((key) => params[key] === expectedParams[key]); + }; +}; + +const getBodyMatcher = (route, fetchMock) => { + const matchPartialBody = fetchMock.getOption('matchPartialBody', route); + const { body: expectedBody } = route; + + debug('Generating body matcher'); + return (url, { body, method = 'get' }) => { + debug('Attempting to match body'); + if (method.toLowerCase() === 'get') { + debug(' GET request - skip matching body'); + // GET requests don’t send a body so the body matcher should be ignored for them + return true; + } + + let sentBody = body; + + try { + debug(' Parsing request body as JSON'); + sentBody = JSON.parse(body); + } catch (err) { + debug(' Failed to parse request body as JSON', err); + } + debug('Expected body:', expectedBody); + debug('Actual body:', sentBody); + if (matchPartialBody) { + debug('matchPartialBody is true - checking for partial match only'); + } + + return ( + sentBody && + (matchPartialBody + ? isSubset(sentBody, expectedBody) + : isEqual(sentBody, expectedBody)) + ); + }; +}; + +const getFullUrlMatcher = (route, matcherUrl, query) => { + // if none of the special syntaxes apply, it's just a simple string match + // but we have to be careful to normalize the url we check and the name + // of the route to allow for e.g. http://it.at.there being indistinguishable + // from http://it.at.there/ once we start generating Request/Url objects + debug(' Matching using full url', matcherUrl); + const expectedUrl = normalizeUrl(matcherUrl); + debug(' Normalised url to:', matcherUrl); + if (route.identifier === matcherUrl) { + debug(' Updating route identifier to match normalized url:', matcherUrl); + route.identifier = expectedUrl; + } + + return (matcherUrl) => { + debug('Expected url:', expectedUrl); + debug('Actual url:', matcherUrl); + if (query && expectedUrl.indexOf('?')) { + debug('Ignoring query string when matching url'); + return matcherUrl.indexOf(expectedUrl) === 0; + } + return normalizeUrl(matcherUrl) === expectedUrl; + }; +}; + +const getFunctionMatcher = ({ functionMatcher }) => { + debug('Detected user defined function matcher', functionMatcher); + return (...args) => { + debug('Calling function matcher with arguments', args); + return functionMatcher(...args); + }; +}; + +const getUrlMatcher = (route) => { + debug('Generating url matcher'); + const { url: matcherUrl, query } = route; + + if (matcherUrl === '*') { + debug(' Using universal * rule to match any url'); + return () => true; + } + + if (matcherUrl instanceof RegExp) { + debug(' Using regular expression to match url:', matcherUrl); + return (url) => matcherUrl.test(url); + } + + if (matcherUrl.href) { + debug(` Using URL object to match url`, matcherUrl); + return getFullUrlMatcher(route, matcherUrl.href, query); + } + + for (const shorthand in stringMatchers) { + if (matcherUrl.indexOf(shorthand + ':') === 0) { + debug(` Using ${shorthand}: pattern to match url`, matcherUrl); + const urlFragment = matcherUrl.replace(new RegExp(`^${shorthand}:`), ''); + return stringMatchers[shorthand](urlFragment); + } + } + + return getFullUrlMatcher(route, matcherUrl, query); +}; + +module.exports = [ + { name: 'query', matcher: getQueryStringMatcher }, + { name: 'method', matcher: getMethodMatcher }, + { name: 'headers', matcher: getHeaderMatcher }, + { name: 'params', matcher: getParamsMatcher }, + { name: 'body', matcher: getBodyMatcher, usesBody: true }, + { name: 'functionMatcher', matcher: getFunctionMatcher }, + { name: 'url', matcher: getUrlMatcher }, +]; diff --git a/cjs/client-legacy.js b/cjs/client-legacy.js new file mode 100644 index 00000000..341eaea5 --- /dev/null +++ b/cjs/client-legacy.js @@ -0,0 +1,5 @@ +require('@babel/core').transform('code', { + plugins: ['transform-runtime'], +}); + +module.exports = require('./client'); diff --git a/cjs/client.js b/cjs/client.js new file mode 100644 index 00000000..e0428dc9 --- /dev/null +++ b/cjs/client.js @@ -0,0 +1,17 @@ +const FetchMock = require('./lib/index'); +const statusTextMap = require('./lib/status-text'); +const theGlobal = typeof window !== 'undefined' ? window : self; +const { setUrlImplementation } = require('./lib/request-utils'); +setUrlImplementation(theGlobal.URL); + +FetchMock.global = theGlobal; +FetchMock.statusTextMap = statusTextMap; + +FetchMock.config = Object.assign(FetchMock.config, { + Promise: theGlobal.Promise, + Request: theGlobal.Request, + Response: theGlobal.Response, + Headers: theGlobal.Headers, +}); + +module.exports = FetchMock.createInstance(); diff --git a/cjs/lib/debug.js b/cjs/lib/debug.js new file mode 100644 index 00000000..a5338ec3 --- /dev/null +++ b/cjs/lib/debug.js @@ -0,0 +1,29 @@ +const debug = require('debug'); + +let debugFunc; +let phase = 'default'; +let namespace = ''; +const newDebug = () => { + debugFunc = namespace + ? debug(`fetch-mock:${phase}:${namespace}`) + : debug(`fetch-mock:${phase}`); +}; + +const newDebugSandbox = (ns) => debug(`fetch-mock:${phase}:${ns}`); + +newDebug(); + +module.exports = { + debug: (...args) => { + debugFunc(...args); + }, + setDebugNamespace: (str) => { + namespace = str; + newDebug(); + }, + setDebugPhase: (str) => { + phase = str || 'default'; + newDebug(); + }, + getDebug: (namespace) => newDebugSandbox(namespace), +}; diff --git a/cjs/lib/fetch-handler.js b/cjs/lib/fetch-handler.js new file mode 100755 index 00000000..d07f9542 --- /dev/null +++ b/cjs/lib/fetch-handler.js @@ -0,0 +1,309 @@ +const { debug, setDebugPhase, getDebug } = require('./debug'); +const responseBuilder = require('./response-builder'); +const requestUtils = require('./request-utils'); +const FetchMock = {}; + +// see https://heycam.github.io/webidl/#aborterror for the standardised interface +// Note that this differs slightly from node-fetch +class AbortError extends Error { + constructor() { + super(...arguments); + this.name = 'AbortError'; + this.message = 'The operation was aborted.'; + + // Do not include this class in the stacktrace + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } +} + +// Patch native fetch to avoid "NotSupportedError:ReadableStream uploading is not supported" in Safari. +// See also https://github.com/wheresrhys/fetch-mock/issues/584 +// See also https://stackoverflow.com/a/50952018/1273406 +const patchNativeFetchForSafari = (nativeFetch) => { + // Try to patch fetch only on Safari + if ( + typeof navigator === 'undefined' || + !navigator.vendor || + navigator.vendor !== 'Apple Computer, Inc.' + ) { + return nativeFetch; + } + // It seems the code is working on Safari thus patch native fetch to avoid the error. + return async (request) => { + const { method } = request; + if (!['POST', 'PUT', 'PATCH'].includes(method)) { + // No patch is required in this case + return nativeFetch(request); + } + const body = await request.clone().text(); + const { + cache, + credentials, + headers, + integrity, + mode, + redirect, + referrer, + } = request; + const init = { + body, + cache, + credentials, + headers, + integrity, + mode, + redirect, + referrer, + method, + }; + return nativeFetch(request.url, init); + }; +}; + +const resolve = async ( + { response, responseIsFetch = false }, + url, + options, + request +) => { + const debug = getDebug('resolve()'); + debug('Recursively resolving function and promise responses'); + // We want to allow things like + // - function returning a Promise for a response + // - delaying (using a timeout Promise) a function's execution to generate + // a response + // Because of this we can't safely check for function before Promisey-ness, + // or vice versa. So to keep it DRY, and flexible, we keep trying until we + // have something that looks like neither Promise nor function + while (true) { + if (typeof response === 'function') { + debug(' Response is a function'); + // in the case of falling back to the network we need to make sure we're using + // the original Request instance, not our normalised url + options + if (responseIsFetch) { + if (request) { + debug(' -> Calling fetch with Request instance'); + return response(request); + } + debug(' -> Calling fetch with url and options'); + return response(url, options); + } else { + debug(' -> Calling response function'); + response = response(url, options, request); + } + } else if (typeof response.then === 'function') { + debug(' Response is a promise'); + debug(' -> Resolving promise'); + response = await response; + } else { + debug(' Response is not a function or a promise'); + debug(' -> Exiting response resolution recursion'); + return response; + } + } +}; + +FetchMock.needsAsyncBodyExtraction = function ({ request }) { + return request && this.routes.some(({ usesBody }) => usesBody); +}; + +FetchMock.fetchHandler = function (url, options) { + setDebugPhase('handle'); + const debug = getDebug('fetchHandler()'); + debug('fetch called with:', url, options); + + const normalizedRequest = requestUtils.normalizeRequest( + url, + options, + this.config.Request + ); + + debug('Request normalised'); + debug(' url', normalizedRequest.url); + debug(' options', normalizedRequest.options); + debug(' request', normalizedRequest.request); + debug(' signal', normalizedRequest.signal); + + if (this.needsAsyncBodyExtraction(normalizedRequest)) { + debug( + 'Need to wait for Body to be streamed before calling router: switching to async mode' + ); + return this._extractBodyThenHandle(normalizedRequest); + } + return this._fetchHandler(normalizedRequest); +}; + +FetchMock._extractBodyThenHandle = async function (normalizedRequest) { + normalizedRequest.options.body = await normalizedRequest.options.body; + return this._fetchHandler(normalizedRequest); +}; + +FetchMock._fetchHandler = function ({ url, options, request, signal }) { + const { route, callLog } = this.executeRouter(url, options, request); + + this.recordCall(callLog); + + // this is used to power the .flush() method + let done; + this._holdingPromises.push(new this.config.Promise((res) => (done = res))); + + // wrapped in this promise to make sure we respect custom Promise + // constructors defined by the user + return new this.config.Promise((res, rej) => { + if (signal) { + debug('signal exists - enabling fetch abort'); + const abort = () => { + debug('aborting fetch'); + // note that DOMException is not available in node.js; + // even node-fetch uses a custom error class: + // https://github.com/bitinn/node-fetch/blob/master/src/abort-error.js + rej( + typeof DOMException !== 'undefined' + ? new DOMException('The operation was aborted.', 'AbortError') + : new AbortError() + ); + done(); + }; + if (signal.aborted) { + debug('signal is already aborted - aborting the fetch'); + abort(); + } + signal.addEventListener('abort', abort); + } + + this.generateResponse({ route, url, options, request, callLog }) + .then(res, rej) + .then(done, done) + .then(() => { + setDebugPhase(); + }); + }); +}; + +FetchMock.fetchHandler.isMock = true; + +FetchMock.executeRouter = function (url, options, request) { + const debug = getDebug('executeRouter()'); + const callLog = { url, options, request, isUnmatched: true }; + debug(`Attempting to match request to a route`); + if (this.getOption('fallbackToNetwork') === 'always') { + debug( + ' Configured with fallbackToNetwork=always - passing through to fetch' + ); + return { + route: { response: this.getNativeFetch(), responseIsFetch: true }, + // BUG - this callLog never used to get sent. Discovered the bug + // but can't fix outside a major release as it will potentially + // cause too much disruption + // + // callLog, + }; + } + + const route = this.router(url, options, request); + + if (route) { + debug(' Matching route found'); + return { + route, + callLog: { + url, + options, + request, + identifier: route.identifier, + }, + }; + } + + if (this.getOption('warnOnFallback')) { + console.warn(`Unmatched ${(options && options.method) || 'GET'} to ${url}`); // eslint-disable-line + } + + if (this.fallbackResponse) { + debug(' No matching route found - using fallbackResponse'); + return { route: { response: this.fallbackResponse }, callLog }; + } + + if (!this.getOption('fallbackToNetwork')) { + throw new Error( + `fetch-mock: No fallback response defined for ${ + (options && options.method) || 'GET' + } to ${url}` + ); + } + + debug(' Configured to fallbackToNetwork - passing through to fetch'); + return { + route: { response: this.getNativeFetch(), responseIsFetch: true }, + callLog, + }; +}; + +FetchMock.generateResponse = async function ({ + route, + url, + options, + request, + callLog = {}, +}) { + const debug = getDebug('generateResponse()'); + const response = await resolve(route, url, options, request); + + // If the response says to throw an error, throw it + // Type checking is to deal with sinon spies having a throws property :-0 + if (response.throws && typeof response !== 'function') { + debug('response.throws is defined - throwing an error'); + throw response.throws; + } + + // If the response is a pre-made Response, respond with it + if (this.config.Response.prototype.isPrototypeOf(response)) { + debug('response is already a Response instance - returning it'); + callLog.response = response; + return response; + } + + // finally, if we need to convert config into a response, we do it + const [realResponse, finalResponse] = responseBuilder({ + url, + responseConfig: response, + fetchMock: this, + route, + }); + + callLog.response = realResponse; + + return finalResponse; +}; + +FetchMock.router = function (url, options, request) { + const route = this.routes.find((route, i) => { + debug(`Trying to match route ${i}`); + return route.matcher(url, options, request); + }); + + if (route) { + return route; + } +}; + +FetchMock.getNativeFetch = function () { + const func = this.realFetch || (this.isSandbox && this.config.fetch); + if (!func) { + throw new Error( + 'fetch-mock: Falling back to network only available on global fetch-mock, or by setting config.fetch on sandboxed fetch-mock' + ); + } + return patchNativeFetchForSafari(func); +}; + +FetchMock.recordCall = function (obj) { + debug('Recording fetch call', obj); + if (obj) { + this._calls.push(obj); + } +}; + +module.exports = FetchMock; diff --git a/cjs/lib/index.js b/cjs/lib/index.js new file mode 100644 index 00000000..8b851dfc --- /dev/null +++ b/cjs/lib/index.js @@ -0,0 +1,75 @@ +const { debug } = require('./debug'); +const setUpAndTearDown = require('./set-up-and-tear-down'); +const fetchHandler = require('./fetch-handler'); +const inspecting = require('./inspecting'); +const Route = require('../Route'); + +const FetchMock = Object.assign({}, fetchHandler, setUpAndTearDown, inspecting); + +FetchMock.addMatcher = function (matcher) { + Route.addMatcher(matcher); +}; + +FetchMock.config = { + fallbackToNetwork: false, + includeContentLength: true, + sendAsJson: true, + warnOnFallback: true, + overwriteRoutes: undefined, +}; + +FetchMock.createInstance = function () { + debug('Creating fetch-mock instance'); + const instance = Object.create(FetchMock); + instance._uncompiledRoutes = (this._uncompiledRoutes || []).slice(); + instance.routes = instance._uncompiledRoutes.map((config) => + this.compileRoute(config) + ); + instance.fallbackResponse = this.fallbackResponse || undefined; + instance.config = Object.assign({}, this.config || FetchMock.config); + instance._calls = []; + instance._holdingPromises = []; + instance.bindMethods(); + return instance; +}; + +FetchMock.compileRoute = function (config) { + return new Route(config, this); +}; + +FetchMock.bindMethods = function () { + this.fetchHandler = FetchMock.fetchHandler.bind(this); + this.reset = this.restore = FetchMock.reset.bind(this); + this.resetHistory = FetchMock.resetHistory.bind(this); + this.resetBehavior = FetchMock.resetBehavior.bind(this); +}; + +FetchMock.sandbox = function () { + debug('Creating sandboxed fetch-mock instance'); + // this construct allows us to create a fetch-mock instance which is also + // a callable function, while circumventing circularity when defining the + // object that this function should be bound to + const fetchMockProxy = (url, options) => sandbox.fetchHandler(url, options); + + const sandbox = Object.assign( + fetchMockProxy, // Ensures that the entire returned object is a callable function + FetchMock, // prototype methods + this.createInstance(), // instance data + { + Headers: this.config.Headers, + Request: this.config.Request, + Response: this.config.Response, + } + ); + + sandbox.bindMethods(); + sandbox.isSandbox = true; + sandbox.default = sandbox; + return sandbox; +}; + +FetchMock.getOption = function (name, route = {}) { + return name in route ? route[name] : this.config[name]; +}; + +module.exports = FetchMock; diff --git a/cjs/lib/inspecting.js b/cjs/lib/inspecting.js new file mode 100644 index 00000000..31e1eed0 --- /dev/null +++ b/cjs/lib/inspecting.js @@ -0,0 +1,215 @@ +const { setDebugPhase, setDebugNamespace, debug } = require('./debug'); +const { normalizeUrl } = require('./request-utils'); +const Route = require('../Route'); +const FetchMock = {}; +const isName = (nameOrMatcher) => + typeof nameOrMatcher === 'string' && /^[\da-zA-Z\-]+$/.test(nameOrMatcher); + +const filterCallsWithMatcher = function (matcher, options = {}, calls) { + ({ matcher } = new Route( + [Object.assign({ matcher, response: 'ok' }, options)], + this + )); + return calls.filter(({ url, options }) => + matcher(normalizeUrl(url), options) + ); +}; + +const formatDebug = (func) => { + return function (...args) { + setDebugPhase('inspect'); + const result = func.call(this, ...args); + setDebugPhase(); + return result; + }; +}; + +const callObjToArray = (obj) => { + if (!obj) { + return undefined; + } + const { url, options, request, identifier, isUnmatched, response } = obj; + const arr = [url, options]; + arr.request = request; + arr.identifier = identifier; + arr.isUnmatched = isUnmatched; + arr.response = response; + return arr; +}; + +FetchMock.filterCalls = function (nameOrMatcher, options) { + debug('Filtering fetch calls'); + let calls = this._calls; + let matcher = '*'; + + if ([true, 'matched'].includes(nameOrMatcher)) { + debug(`Filter provided is ${nameOrMatcher}. Returning matched calls only`); + calls = calls.filter(({ isUnmatched }) => !isUnmatched); + } else if ([false, 'unmatched'].includes(nameOrMatcher)) { + debug( + `Filter provided is ${nameOrMatcher}. Returning unmatched calls only` + ); + calls = calls.filter(({ isUnmatched }) => isUnmatched); + } else if (typeof nameOrMatcher === 'undefined') { + debug(`Filter provided is undefined. Returning all calls`); + calls = calls; + } else if (isName(nameOrMatcher)) { + debug( + `Filter provided, looks like the name of a named route. Returning only calls handled by that route` + ); + calls = calls.filter(({ identifier }) => identifier === nameOrMatcher); + } else { + matcher = nameOrMatcher === '*' ? '*' : normalizeUrl(nameOrMatcher); + if (this.routes.some(({ identifier }) => identifier === matcher)) { + debug( + `Filter provided, ${nameOrMatcher}, identifies a route. Returning only calls handled by that route` + ); + calls = calls.filter((call) => call.identifier === matcher); + } + } + + if ((options || matcher !== '*') && calls.length) { + if (typeof options === 'string') { + options = { method: options }; + } + debug( + 'Compiling filter and options to route in order to filter all calls', + nameOrMatcher + ); + calls = filterCallsWithMatcher.call(this, matcher, options, calls); + } + debug(`Retrieved ${calls.length} calls`); + return calls.map(callObjToArray); +}; + +FetchMock.calls = formatDebug(function (nameOrMatcher, options) { + debug('retrieving matching calls'); + return this.filterCalls(nameOrMatcher, options); +}); + +FetchMock.lastCall = formatDebug(function (nameOrMatcher, options) { + debug('retrieving last matching call'); + return [...this.filterCalls(nameOrMatcher, options)].pop(); +}); + +FetchMock.lastUrl = formatDebug(function (nameOrMatcher, options) { + debug('retrieving url of last matching call'); + return (this.lastCall(nameOrMatcher, options) || [])[0]; +}); + +FetchMock.lastOptions = formatDebug(function (nameOrMatcher, options) { + debug('retrieving options of last matching call'); + return (this.lastCall(nameOrMatcher, options) || [])[1]; +}); + +FetchMock.lastResponse = formatDebug(function (nameOrMatcher, options) { + debug('retrieving respose of last matching call'); + console.warn(`When doing all the following: +- using node-fetch +- responding with a real network response (using spy() or fallbackToNetwork) +- using \`fetchMock.LastResponse()\` +- awaiting the body content +... the response will hang unless your source code also awaits the response body. +This is an unavoidable consequence of the nodejs implementation of streams. +`); + const response = (this.lastCall(nameOrMatcher, options) || []).response; + try { + const clonedResponse = response.clone(); + return clonedResponse; + } catch (err) { + Object.entries(response._fmResults).forEach(([name, result]) => { + response[name] = () => result; + }); + return response; + } +}); + +FetchMock.called = formatDebug(function (nameOrMatcher, options) { + debug('checking if matching call was made'); + return Boolean(this.filterCalls(nameOrMatcher, options).length); +}); + +FetchMock.flush = formatDebug(async function (waitForResponseMethods) { + setDebugNamespace('flush'); + debug( + `flushing all fetch calls. ${ + waitForResponseMethods ? '' : 'Not ' + }waiting for response bodies to complete download` + ); + + const queuedPromises = this._holdingPromises; + this._holdingPromises = []; + debug(`${queuedPromises.length} fetch calls to be awaited`); + + await Promise.all(queuedPromises); + debug(`All fetch calls have completed`); + if (waitForResponseMethods && this._holdingPromises.length) { + debug(`Awaiting all fetch bodies to download`); + await this.flush(waitForResponseMethods); + debug(`All fetch bodies have completed downloading`); + } + setDebugNamespace(); +}); + +FetchMock.done = formatDebug(function (nameOrMatcher) { + setDebugPhase('inspect'); + setDebugNamespace('done'); + debug('Checking to see if expected calls have been made'); + let routesToCheck; + + if (nameOrMatcher && typeof nameOrMatcher !== 'boolean') { + debug( + 'Checking to see if expected calls have been made for single route:', + nameOrMatcher + ); + routesToCheck = [{ identifier: nameOrMatcher }]; + } else { + debug('Checking to see if expected calls have been made for all routes'); + routesToCheck = this.routes; + } + + // Can't use array.every because would exit after first failure, which would + // break the logging + const result = routesToCheck + .map(({ identifier }) => { + if (!this.called(identifier)) { + debug('No calls made for route:', identifier); + console.warn(`Warning: ${identifier} not called`); // eslint-disable-line + return false; + } + + const expectedTimes = ( + this.routes.find((r) => r.identifier === identifier) || {} + ).repeat; + + if (!expectedTimes) { + debug( + 'Route has been called at least once, and no expectation of more set:', + identifier + ); + return true; + } + const actualTimes = this.filterCalls(identifier).length; + + debug(`Route called ${actualTimes} times:`, identifier); + if (expectedTimes > actualTimes) { + debug( + `Route called ${actualTimes} times, but expected ${expectedTimes}:`, + identifier + ); + console.warn( + `Warning: ${identifier} only called ${actualTimes} times, but ${expectedTimes} expected` + ); // eslint-disable-line + return false; + } else { + return true; + } + }) + .every((isDone) => isDone); + + setDebugNamespace(); + setDebugPhase(); + return result; +}); + +module.exports = FetchMock; diff --git a/cjs/lib/request-utils.js b/cjs/lib/request-utils.js new file mode 100644 index 00000000..b6869672 --- /dev/null +++ b/cjs/lib/request-utils.js @@ -0,0 +1,135 @@ +let URL; +// https://stackoverflow.com/a/19709846/308237 +// split, URL constructor does not support protocol-relative urls +const absoluteUrlRX = new RegExp('^[a-z]+://', 'i'); +const protocolRelativeUrlRX = new RegExp('^//', 'i'); + +const headersToArray = (headers) => { + // node-fetch 1 Headers + if (typeof headers.raw === 'function') { + return Object.entries(headers.raw()); + } else if (headers[Symbol.iterator]) { + return [...headers]; + } else { + return Object.entries(headers); + } +}; + +const zipObject = (entries) => + entries.reduce((obj, [key, val]) => Object.assign(obj, { [key]: val }), {}); + +const normalizeUrl = (url) => { + if ( + typeof url === 'function' || + url instanceof RegExp || + /^(begin|end|glob|express|path)\:/.test(url) + ) { + return url; + } + if (absoluteUrlRX.test(url)) { + const u = new URL(url); + return u.href; + } else if (protocolRelativeUrlRX.test(url)) { + const u = new URL(url, 'http://dummy'); + return u.href; + } else { + const u = new URL(url, 'http://dummy'); + return u.pathname + u.search; + } +}; + +const extractBody = async (request) => { + try { + // node-fetch + if ('body' in request) { + return request.body.toString(); + } + // fetch + return request.clone().text(); + } catch (err) {} +}; + +module.exports = { + setUrlImplementation: (it) => { + URL = it; + }, + normalizeRequest: (url, options, Request) => { + if (Request.prototype.isPrototypeOf(url)) { + const derivedOptions = { + method: url.method, + }; + + const body = extractBody(url); + + if (typeof body !== 'undefined') { + derivedOptions.body = body; + } + + const normalizedRequestObject = { + url: normalizeUrl(url.url), + options: Object.assign(derivedOptions, options), + request: url, + signal: (options && options.signal) || url.signal, + }; + + const headers = headersToArray(url.headers); + + if (headers.length) { + normalizedRequestObject.options.headers = zipObject(headers); + } + return normalizedRequestObject; + } else if ( + typeof url === 'string' || + // horrible URL object duck-typing + (typeof url === 'object' && 'href' in url) + ) { + return { + url: normalizeUrl(url), + options: options, + signal: options && options.signal, + }; + } else if (typeof url === 'object') { + throw new TypeError( + 'fetch-mock: Unrecognised Request object. Read the Config and Installation sections of the docs' + ); + } else { + throw new TypeError('fetch-mock: Invalid arguments passed to fetch'); + } + }, + normalizeUrl, + getPath: (url) => { + const u = absoluteUrlRX.test(url) + ? new URL(url) + : new URL(url, 'http://dummy'); + return u.pathname; + }, + + getQuery: (url) => { + const u = absoluteUrlRX.test(url) + ? new URL(url) + : new URL(url, 'http://dummy'); + return u.search ? u.search.substr(1) : ''; + }, + headers: { + normalize: (headers) => zipObject(headersToArray(headers)), + toLowerCase: (headers) => + Object.keys(headers).reduce((obj, k) => { + obj[k.toLowerCase()] = headers[k]; + return obj; + }, {}), + equal: (actualHeader, expectedHeader) => { + actualHeader = Array.isArray(actualHeader) + ? actualHeader + : [actualHeader]; + expectedHeader = Array.isArray(expectedHeader) + ? expectedHeader + : [expectedHeader]; + + if (actualHeader.length !== expectedHeader.length) { + return false; + } + + return actualHeader.every((val, i) => val === expectedHeader[i]); + }, + }, +}; diff --git a/cjs/lib/response-builder.js b/cjs/lib/response-builder.js new file mode 100644 index 00000000..a274f526 --- /dev/null +++ b/cjs/lib/response-builder.js @@ -0,0 +1,197 @@ +const { getDebug } = require('./debug'); +const responseConfigProps = [ + 'body', + 'headers', + 'throws', + 'status', + 'redirectUrl', +]; + +class ResponseBuilder { + constructor(options) { + this.debug = getDebug('ResponseBuilder()'); + this.debug('Response builder created with options', options); + Object.assign(this, options); + } + + exec() { + this.debug('building response'); + this.normalizeResponseConfig(); + this.constructFetchOpts(); + this.constructResponseBody(); + + const realResponse = new this.fetchMock.config.Response( + this.body, + this.options + ); + const proxyResponse = this.buildObservableResponse(realResponse); + return [realResponse, proxyResponse]; + } + + sendAsObject() { + if (responseConfigProps.some((prop) => this.responseConfig[prop])) { + if ( + Object.keys(this.responseConfig).every((key) => + responseConfigProps.includes(key) + ) + ) { + return false; + } else { + return true; + } + } else { + return true; + } + } + + normalizeResponseConfig() { + // If the response config looks like a status, start to generate a simple response + if (typeof this.responseConfig === 'number') { + this.debug('building response using status', this.responseConfig); + this.responseConfig = { + status: this.responseConfig, + }; + // If the response config is not an object, or is an object that doesn't use + // any reserved properties, assume it is meant to be the body of the response + } else if (typeof this.responseConfig === 'string' || this.sendAsObject()) { + this.debug('building text response from', this.responseConfig); + this.responseConfig = { + body: this.responseConfig, + }; + } + } + + validateStatus(status) { + if (!status) { + this.debug('No status provided. Defaulting to 200'); + return 200; + } + + if ( + (typeof status === 'number' && + parseInt(status, 10) !== status && + status >= 200) || + status < 600 + ) { + this.debug('Valid status provided', status); + return status; + } + + throw new TypeError(`fetch-mock: Invalid status ${status} passed on response object. +To respond with a JSON object that has status as a property assign the object to body +e.g. {"body": {"status: "registered"}}`); + } + + constructFetchOpts() { + this.options = this.responseConfig.options || {}; + this.options.url = this.responseConfig.redirectUrl || this.url; + this.options.status = this.validateStatus(this.responseConfig.status); + this.options.statusText = this.fetchMock.statusTextMap[ + String(this.options.status) + ]; + + // Set up response headers. The empty object is to cope with + // new Headers(undefined) throwing in Chrome + // https://code.google.com/p/chromium/issues/detail?id=335871 + this.options.headers = new this.fetchMock.config.Headers( + this.responseConfig.headers || {} + ); + } + + getOption(name) { + return this.fetchMock.getOption(name, this.route); + } + + convertToJson() { + // convert to json if we need to + if ( + this.getOption('sendAsJson') && + this.responseConfig.body != null && //eslint-disable-line + typeof this.body === 'object' + ) { + this.debug('Stringifying JSON response body'); + this.body = JSON.stringify(this.body); + if (!this.options.headers.has('Content-Type')) { + this.options.headers.set('Content-Type', 'application/json'); + } + } + } + + setContentLength() { + // add a Content-Length header if we need to + if ( + this.getOption('includeContentLength') && + typeof this.body === 'string' && + !this.options.headers.has('Content-Length') + ) { + this.debug('Setting content-length header:', this.body.length.toString()); + this.options.headers.set('Content-Length', this.body.length.toString()); + } + } + + constructResponseBody() { + // start to construct the body + this.body = this.responseConfig.body; + this.convertToJson(); + this.setContentLength(); + + // On the server we need to manually construct the readable stream for the + // Response object (on the client this done automatically) + if (this.Stream) { + this.debug('Creating response stream'); + const stream = new this.Stream.Readable(); + if (this.body != null) { //eslint-disable-line + stream.push(this.body, 'utf-8'); + } + stream.push(null); + this.body = stream; + } + this.body = this.body; + } + + buildObservableResponse(response) { + const fetchMock = this.fetchMock; + response._fmResults = {}; + // Using a proxy means we can set properties that may not be writable on + // the original Response. It also means we can track the resolution of + // promises returned by res.json(), res.text() etc + this.debug('Wrapping Response in ES proxy for observability'); + return new Proxy(response, { + get: (originalResponse, name) => { + if (this.responseConfig.redirectUrl) { + if (name === 'url') { + this.debug( + 'Retrieving redirect url', + this.responseConfig.redirectUrl + ); + return this.responseConfig.redirectUrl; + } + + if (name === 'redirected') { + this.debug('Retrieving redirected status', true); + return true; + } + } + + if (typeof originalResponse[name] === 'function') { + this.debug('Wrapping body promises in ES proxies for observability'); + return new Proxy(originalResponse[name], { + apply: (func, thisArg, args) => { + this.debug(`Calling res.${name}`); + const result = func.apply(response, args); + if (result.then) { + fetchMock._holdingPromises.push(result.catch(() => null)); + originalResponse._fmResults[name] = result; + } + return result; + }, + }); + } + + return originalResponse[name]; + }, + }); + } +} + +module.exports = (options) => new ResponseBuilder(options).exec(); diff --git a/cjs/lib/set-up-and-tear-down.js b/cjs/lib/set-up-and-tear-down.js new file mode 100644 index 00000000..42b13569 --- /dev/null +++ b/cjs/lib/set-up-and-tear-down.js @@ -0,0 +1,150 @@ +const { debug, setDebugPhase } = require('./debug'); +const FetchMock = {}; + +FetchMock.mock = function (...args) { + setDebugPhase('setup'); + if (args.length) { + this.addRoute(args); + } + + return this._mock(); +}; + +FetchMock.addRoute = function (uncompiledRoute) { + debug('Adding route', uncompiledRoute); + const route = this.compileRoute(uncompiledRoute); + const clashes = this.routes.filter(({ identifier, method }) => { + const isMatch = + typeof identifier === 'function' + ? identifier === route.identifier + : String(identifier) === String(route.identifier); + return isMatch && (!method || !route.method || method === route.method); + }); + + if (this.getOption('overwriteRoutes', route) === false || !clashes.length) { + this._uncompiledRoutes.push(uncompiledRoute); + return this.routes.push(route); + } + + if (this.getOption('overwriteRoutes', route) === true) { + clashes.forEach((clash) => { + const index = this.routes.indexOf(clash); + this._uncompiledRoutes.splice(index, 1, uncompiledRoute); + this.routes.splice(index, 1, route); + }); + return this.routes; + } + + if (clashes.length) { + throw new Error( + 'fetch-mock: Adding route with same name or matcher as existing route. See `overwriteRoutes` option.' + ); + } + + this._uncompiledRoutes.push(uncompiledRoute); + this.routes.push(route); +}; + +FetchMock._mock = function () { + if (!this.isSandbox) { + // Do this here rather than in the constructor to ensure it's scoped to the test + this.realFetch = this.realFetch || this.global.fetch; + this.global.fetch = this.fetchHandler; + } + setDebugPhase(); + return this; +}; + +FetchMock.catch = function (response) { + if (this.fallbackResponse) { + console.warn( + 'calling fetchMock.catch() twice - are you sure you want to overwrite the previous fallback response' + ); // eslint-disable-line + } + this.fallbackResponse = response || 'ok'; + return this._mock(); +}; + +FetchMock.spy = function (route) { + // even though ._mock() is called by .mock() and .catch() we still need to + // call it here otherwise .getNativeFetch() won't be able to use the reference + // to .realFetch that ._mock() sets up + this._mock(); + return route + ? this.mock(route, this.getNativeFetch()) + : this.catch(this.getNativeFetch()); +}; + +const defineShorthand = (methodName, underlyingMethod, shorthandOptions) => { + FetchMock[methodName] = function (matcher, response, options) { + return this[underlyingMethod]( + matcher, + response, + Object.assign(options || {}, shorthandOptions) + ); + }; +}; + +const defineGreedyShorthand = (methodName, underlyingMethod) => { + FetchMock[methodName] = function (response, options) { + return this[underlyingMethod]({}, response, options); + }; +}; + +defineShorthand('sticky', 'mock', { sticky: true }); +defineShorthand('once', 'mock', { repeat: 1 }); +defineGreedyShorthand('any', 'mock'); +defineGreedyShorthand('anyOnce', 'once'); + +['get', 'post', 'put', 'delete', 'head', 'patch'].forEach((method) => { + defineShorthand(method, 'mock', { method }); + defineShorthand(`${method}Once`, 'once', { method }); + defineGreedyShorthand(`${method}Any`, method); + defineGreedyShorthand(`${method}AnyOnce`, `${method}Once`); +}); + +const mochaAsyncHookWorkaround = (options) => { + // HACK workaround for this https://github.com/mochajs/mocha/issues/4280 + // Note that it doesn't matter that we call it _before_ carrying out all + // the things resetBehavior does as everything in there is synchronous + if (typeof options === 'function') { + console.warn(`Deprecated: Passing fetch-mock reset methods +directly in as handlers for before/after test runner hooks. +Wrap in an arrow function instead e.g. \`() => fetchMock.restore()\``); + options(); + } +}; + +const getRouteRemover = ({ sticky: removeStickyRoutes }) => (routes) => + removeStickyRoutes ? [] : routes.filter(({ sticky }) => sticky); + +FetchMock.resetBehavior = function (options = {}) { + mochaAsyncHookWorkaround(options); + const removeRoutes = getRouteRemover(options); + + this.routes = removeRoutes(this.routes); + this._uncompiledRoutes = removeRoutes(this._uncompiledRoutes); + + if (this.realFetch && !this.routes.length) { + this.global.fetch = this.realFetch; + this.realFetch = undefined; + } + + this.fallbackResponse = undefined; + return this; +}; + +FetchMock.resetHistory = function () { + this._calls = []; + this._holdingPromises = []; + this.routes.forEach((route) => route.reset && route.reset()); + return this; +}; + +FetchMock.restore = FetchMock.reset = function (options) { + this.resetBehavior(options); + this.resetHistory(); + return this; +}; + +module.exports = FetchMock; diff --git a/cjs/lib/status-text.js b/cjs/lib/status-text.js new file mode 100644 index 00000000..beed90e5 --- /dev/null +++ b/cjs/lib/status-text.js @@ -0,0 +1,66 @@ +const statusTextMap = { + 100: 'Continue', + 101: 'Switching Protocols', + 102: 'Processing', + 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: 'Unordered Collection', + 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', +}; + +module.exports = statusTextMap; diff --git a/cjs/package.json b/cjs/package.json new file mode 100644 index 00000000..b731bd61 --- /dev/null +++ b/cjs/package.json @@ -0,0 +1 @@ +{"type": "commonjs"} diff --git a/cjs/server.js b/cjs/server.js new file mode 100644 index 00000000..92f2be5f --- /dev/null +++ b/cjs/server.js @@ -0,0 +1,32 @@ +// avoid circular dependency when using jest.mock() +let fetch; +try { + // note that jest is not a global, but is injected somehow into + // the environment. So we can't be safe and check for global.jest + // Hence the try/catch + fetch = jest.requireActual('node-fetch'); //eslint-disable-line no-undef +} catch (e) { + fetch = require('node-fetch'); +} +const Request = fetch.Request; +const Response = fetch.Response; +const Headers = fetch.Headers; +const Stream = require('stream'); +const FetchMock = require('./lib/index'); +const http = require('http'); +const { setUrlImplementation } = require('./lib/request-utils'); +setUrlImplementation(require('whatwg-url').URL); + +FetchMock.global = global; +FetchMock.statusTextMap = http.STATUS_CODES; +FetchMock.Stream = Stream; + +FetchMock.config = Object.assign(FetchMock.config, { + Promise, + Request, + Response, + Headers, + fetch, +}); + +module.exports = FetchMock.createInstance(); diff --git a/es5/Route/index.js b/es5/Route/index.js new file mode 100644 index 00000000..c7c59b7b --- /dev/null +++ b/es5/Route/index.js @@ -0,0 +1,206 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); + +var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); + +var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); + +var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof")); + +var builtInMatchers = require('./matchers'); + +var _require = require('../lib/debug'), + debug = _require.debug, + setDebugNamespace = _require.setDebugNamespace, + getDebug = _require.getDebug; + +var isUrlMatcher = function isUrlMatcher(matcher) { + return matcher instanceof RegExp || typeof matcher === 'string' || (0, _typeof2["default"])(matcher) === 'object' && 'href' in matcher; +}; + +var isFunctionMatcher = function isFunctionMatcher(matcher) { + return typeof matcher === 'function'; +}; + +var Route = /*#__PURE__*/function () { + function Route(args, fetchMock) { + (0, _classCallCheck2["default"])(this, Route); + this.fetchMock = fetchMock; + var debug = getDebug('compileRoute()'); + debug('Compiling route'); + this.init(args); + this.sanitize(); + this.validate(); + this.generateMatcher(); + this.limit(); + this.delayResponse(); + } + + (0, _createClass2["default"])(Route, [{ + key: "validate", + value: function validate() { + var _this = this; + + if (!('response' in this)) { + throw new Error('fetch-mock: Each route must define a response'); + } + + if (!Route.registeredMatchers.some(function (_ref) { + var name = _ref.name; + return name in _this; + })) { + throw new Error("fetch-mock: Each route must specify some criteria for matching calls to fetch. To match all calls use '*'"); + } + } + }, { + key: "init", + value: function init(args) { + var _args = (0, _slicedToArray2["default"])(args, 3), + matcher = _args[0], + response = _args[1], + _args$ = _args[2], + options = _args$ === void 0 ? {} : _args$; + + var routeConfig = {}; + + if (isUrlMatcher(matcher) || isFunctionMatcher(matcher)) { + routeConfig.matcher = matcher; + } else { + Object.assign(routeConfig, matcher); + } + + if (typeof response !== 'undefined') { + routeConfig.response = response; + } + + Object.assign(routeConfig, options); + Object.assign(this, routeConfig); + } + }, { + key: "sanitize", + value: function sanitize() { + var debug = getDebug('sanitize()'); + debug('Sanitizing route properties'); + + if (this.method) { + debug("Converting method ".concat(this.method, " to lower case")); + this.method = this.method.toLowerCase(); + } + + if (isUrlMatcher(this.matcher)) { + debug('Mock uses a url matcher', this.matcher); + this.url = this.matcher; + delete this.matcher; + } + + this.functionMatcher = this.matcher || this.functionMatcher; + debug('Setting route.identifier...'); + debug(" route.name is ".concat(this.name)); + debug(" route.url is ".concat(this.url)); + debug(" route.functionMatcher is ".concat(this.functionMatcher)); + this.identifier = this.name || this.url || this.functionMatcher; + debug(" -> route.identifier set to ".concat(this.identifier)); + } + }, { + key: "generateMatcher", + value: function generateMatcher() { + var _this2 = this; + + setDebugNamespace('generateMatcher()'); + debug('Compiling matcher for route'); + var activeMatchers = Route.registeredMatchers.map(function (_ref2) { + var name = _ref2.name, + matcher = _ref2.matcher, + usesBody = _ref2.usesBody; + return _this2[name] && { + matcher: matcher(_this2, _this2.fetchMock), + usesBody: usesBody + }; + }).filter(function (matcher) { + return Boolean(matcher); + }); + this.usesBody = activeMatchers.some(function (_ref3) { + var usesBody = _ref3.usesBody; + return usesBody; + }); + debug('Compiled matcher for route'); + setDebugNamespace(); + + this.matcher = function (url) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var request = arguments.length > 2 ? arguments[2] : undefined; + return activeMatchers.every(function (_ref4) { + var matcher = _ref4.matcher; + return matcher(url, options, request); + }); + }; + } + }, { + key: "limit", + value: function limit() { + var _this3 = this; + + var debug = getDebug('limit()'); + debug('Limiting number of requests to handle by route'); + + if (!this.repeat) { + debug(' No `repeat` value set on route. Will match any number of requests'); + return; + } + + debug(" Route set to repeat ".concat(this.repeat, " times")); + var matcher = this.matcher; + var timesLeft = this.repeat; + + this.matcher = function (url, options) { + var match = timesLeft && matcher(url, options); + + if (match) { + timesLeft--; + return true; + } + }; + + this.reset = function () { + return timesLeft = _this3.repeat; + }; + } + }, { + key: "delayResponse", + value: function delayResponse() { + var _this4 = this; + + var debug = getDebug('delayResponse()'); + debug("Applying response delay settings"); + + if (this.delay) { + debug(" Wrapping response in delay of ".concat(this.delay, " miliseconds")); + var response = this.response; + + this.response = function () { + debug("Delaying response by ".concat(_this4.delay, " miliseconds")); + return new Promise(function (res) { + return setTimeout(function () { + return res(response); + }, _this4.delay); + }); + }; + } else { + debug(" No delay set on route. Will respond 'immediately' (but asynchronously)"); + } + } + }], [{ + key: "addMatcher", + value: function addMatcher(matcher) { + Route.registeredMatchers.push(matcher); + } + }]); + return Route; +}(); + +Route.registeredMatchers = []; +builtInMatchers.forEach(Route.addMatcher); +module.exports = Route; \ No newline at end of file diff --git a/es5/Route/matchers.js b/es5/Route/matchers.js new file mode 100644 index 00000000..a30b7656 --- /dev/null +++ b/es5/Route/matchers.js @@ -0,0 +1,306 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); + +var _require = require('../lib/debug'), + debug = _require.debug; + +var _glob = require('glob-to-regexp'); + +var pathToRegexp = require('path-to-regexp'); + +var querystring = require('querystring'); + +var isSubset = require('is-subset'); + +var _require2 = require('../lib/request-utils'), + headerUtils = _require2.headers, + getPath = _require2.getPath, + getQuery = _require2.getQuery, + normalizeUrl = _require2.normalizeUrl; + +var isEqual = require('lodash.isequal'); + +var debuggableUrlFunc = function debuggableUrlFunc(func) { + return function (url) { + debug('Actual url:', url); + return func(url); + }; +}; + +var stringMatchers = { + begin: function begin(targetString) { + return debuggableUrlFunc(function (url) { + return url.indexOf(targetString) === 0; + }); + }, + end: function end(targetString) { + return debuggableUrlFunc(function (url) { + return url.substr(-targetString.length) === targetString; + }); + }, + glob: function glob(targetString) { + var urlRX = _glob(targetString); + + return debuggableUrlFunc(function (url) { + return urlRX.test(url); + }); + }, + express: function express(targetString) { + var urlRX = pathToRegexp(targetString); + return debuggableUrlFunc(function (url) { + return urlRX.test(getPath(url)); + }); + }, + path: function path(targetString) { + return debuggableUrlFunc(function (url) { + return getPath(url) === targetString; + }); + } +}; + +var getHeaderMatcher = function getHeaderMatcher(_ref) { + var expectedHeaders = _ref.headers; + debug('Generating header matcher'); + + if (!expectedHeaders) { + debug(' No header expectations defined - skipping'); + return; + } + + var expectation = headerUtils.toLowerCase(expectedHeaders); + debug(' Expected headers:', expectation); + return function (url, _ref2) { + var _ref2$headers = _ref2.headers, + headers = _ref2$headers === void 0 ? {} : _ref2$headers; + debug('Attempting to match headers'); + var lowerCaseHeaders = headerUtils.toLowerCase(headerUtils.normalize(headers)); + debug(' Expected headers:', expectation); + debug(' Actual headers:', lowerCaseHeaders); + return Object.keys(expectation).every(function (headerName) { + return headerUtils.equal(lowerCaseHeaders[headerName], expectation[headerName]); + }); + }; +}; + +var getMethodMatcher = function getMethodMatcher(_ref3) { + var expectedMethod = _ref3.method; + debug('Generating method matcher'); + + if (!expectedMethod) { + debug(' No method expectations defined - skipping'); + return; + } + + debug(' Expected method:', expectedMethod); + return function (url, _ref4) { + var method = _ref4.method; + debug('Attempting to match method'); + var actualMethod = method ? method.toLowerCase() : 'get'; + debug(' Expected method:', expectedMethod); + debug(' Actual method:', actualMethod); + return expectedMethod === actualMethod; + }; +}; + +var getQueryStringMatcher = function getQueryStringMatcher(_ref5) { + var passedQuery = _ref5.query; + debug('Generating query parameters matcher'); + + if (!passedQuery) { + debug(' No query parameters expectations defined - skipping'); + return; + } + + var expectedQuery = querystring.parse(querystring.stringify(passedQuery)); + debug(' Expected query parameters:', passedQuery); + var keys = Object.keys(expectedQuery); + return function (url) { + debug('Attempting to match query parameters'); + var query = querystring.parse(getQuery(url)); + debug(' Expected query parameters:', expectedQuery); + debug(' Actual query parameters:', query); + return keys.every(function (key) { + if (Array.isArray(query[key])) { + if (!Array.isArray(expectedQuery[key])) { + return false; + } else { + return isEqual(query[key].sort(), expectedQuery[key].sort()); + } + } + + return query[key] === expectedQuery[key]; + }); + }; +}; + +var getParamsMatcher = function getParamsMatcher(_ref6) { + var expectedParams = _ref6.params, + matcherUrl = _ref6.url; + debug('Generating path parameters matcher'); + + if (!expectedParams) { + debug(' No path parameters expectations defined - skipping'); + return; + } + + if (!/express:/.test(matcherUrl)) { + throw new Error('fetch-mock: matching on params is only possible when using an express: matcher'); + } + + debug(' Expected path parameters:', expectedParams); + var expectedKeys = Object.keys(expectedParams); + var keys = []; + var re = pathToRegexp(matcherUrl.replace(/^express:/, ''), keys); + return function (url) { + debug('Attempting to match path parameters'); + var vals = re.exec(getPath(url)) || []; + vals.shift(); + var params = keys.reduce(function (map, _ref7, i) { + var name = _ref7.name; + return vals[i] ? Object.assign(map, (0, _defineProperty2["default"])({}, name, vals[i])) : map; + }, {}); + debug(' Expected path parameters:', expectedParams); + debug(' Actual path parameters:', params); + return expectedKeys.every(function (key) { + return params[key] === expectedParams[key]; + }); + }; +}; + +var getBodyMatcher = function getBodyMatcher(route, fetchMock) { + var matchPartialBody = fetchMock.getOption('matchPartialBody', route); + var expectedBody = route.body; + debug('Generating body matcher'); + return function (url, _ref8) { + var body = _ref8.body, + _ref8$method = _ref8.method, + method = _ref8$method === void 0 ? 'get' : _ref8$method; + debug('Attempting to match body'); + + if (method.toLowerCase() === 'get') { + debug(' GET request - skip matching body'); // GET requests don’t send a body so the body matcher should be ignored for them + + return true; + } + + var sentBody = body; + + try { + debug(' Parsing request body as JSON'); + sentBody = JSON.parse(body); + } catch (err) { + debug(' Failed to parse request body as JSON', err); + } + + debug('Expected body:', expectedBody); + debug('Actual body:', sentBody); + + if (matchPartialBody) { + debug('matchPartialBody is true - checking for partial match only'); + } + + return sentBody && (matchPartialBody ? isSubset(sentBody, expectedBody) : isEqual(sentBody, expectedBody)); + }; +}; + +var getFullUrlMatcher = function getFullUrlMatcher(route, matcherUrl, query) { + // if none of the special syntaxes apply, it's just a simple string match + // but we have to be careful to normalize the url we check and the name + // of the route to allow for e.g. http://it.at.there being indistinguishable + // from http://it.at.there/ once we start generating Request/Url objects + debug(' Matching using full url', matcherUrl); + var expectedUrl = normalizeUrl(matcherUrl); + debug(' Normalised url to:', matcherUrl); + + if (route.identifier === matcherUrl) { + debug(' Updating route identifier to match normalized url:', matcherUrl); + route.identifier = expectedUrl; + } + + return function (matcherUrl) { + debug('Expected url:', expectedUrl); + debug('Actual url:', matcherUrl); + + if (query && expectedUrl.indexOf('?')) { + debug('Ignoring query string when matching url'); + return matcherUrl.indexOf(expectedUrl) === 0; + } + + return normalizeUrl(matcherUrl) === expectedUrl; + }; +}; + +var getFunctionMatcher = function getFunctionMatcher(_ref9) { + var functionMatcher = _ref9.functionMatcher; + debug('Detected user defined function matcher', functionMatcher); + return function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + debug('Calling function matcher with arguments', args); + return functionMatcher.apply(void 0, args); + }; +}; + +var getUrlMatcher = function getUrlMatcher(route) { + debug('Generating url matcher'); + var matcherUrl = route.url, + query = route.query; + + if (matcherUrl === '*') { + debug(' Using universal * rule to match any url'); + return function () { + return true; + }; + } + + if (matcherUrl instanceof RegExp) { + debug(' Using regular expression to match url:', matcherUrl); + return function (url) { + return matcherUrl.test(url); + }; + } + + if (matcherUrl.href) { + debug(" Using URL object to match url", matcherUrl); + return getFullUrlMatcher(route, matcherUrl.href, query); + } + + for (var shorthand in stringMatchers) { + if (matcherUrl.indexOf(shorthand + ':') === 0) { + debug(" Using ".concat(shorthand, ": pattern to match url"), matcherUrl); + var urlFragment = matcherUrl.replace(new RegExp("^".concat(shorthand, ":")), ''); + return stringMatchers[shorthand](urlFragment); + } + } + + return getFullUrlMatcher(route, matcherUrl, query); +}; + +module.exports = [{ + name: 'query', + matcher: getQueryStringMatcher +}, { + name: 'method', + matcher: getMethodMatcher +}, { + name: 'headers', + matcher: getHeaderMatcher +}, { + name: 'params', + matcher: getParamsMatcher +}, { + name: 'body', + matcher: getBodyMatcher, + usesBody: true +}, { + name: 'functionMatcher', + matcher: getFunctionMatcher +}, { + name: 'url', + matcher: getUrlMatcher +}]; \ No newline at end of file diff --git a/es5/client-bundle.js b/es5/client-bundle.js new file mode 100644 index 00000000..1ac31eb3 --- /dev/null +++ b/es5/client-bundle.js @@ -0,0 +1,6559 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.fetchMock = factory()); +}(this, (function () { 'use strict'; + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; + } + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + /** + * Helpers. + */ + + var s = 1000; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + + /** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + + var ms = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); + }; + + /** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + + function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } + } + + /** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; + } + + /** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; + } + + /** + * Pluralization helper. + */ + + function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); + } + + /** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = ms; + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; + } + + var common = setup; + + var browser$1 = createCommonjsModule(function (module, exports) { + /* eslint-env browser */ + + /** + * This is the web browser implementation of `debug()`. + */ + + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.storage = localstorage(); + exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; + })(); + + /** + * Colors. + */ + + exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' + ]; + + /** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + + // eslint-disable-next-line complexity + function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); + } + + /** + * Colorize log arguments if enabled. + * + * @api public + */ + + function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); + } + + /** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ + exports.log = console.debug || console.log || (() => {}); + + /** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + } + + /** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; + } + + /** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + + function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + } + + module.exports = common(exports); + + const {formatters} = module.exports; + + /** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + + formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } + }; + }); + var browser_1 = browser$1.formatArgs; + var browser_2 = browser$1.save; + var browser_3 = browser$1.load; + var browser_4 = browser$1.useColors; + var browser_5 = browser$1.storage; + var browser_6 = browser$1.destroy; + var browser_7 = browser$1.colors; + var browser_8 = browser$1.log; + + var debugFunc; + var phase = 'default'; + var namespace = ''; + + var newDebug = function newDebug() { + debugFunc = namespace ? browser$1("fetch-mock:".concat(phase, ":").concat(namespace)) : browser$1("fetch-mock:".concat(phase)); + }; + + var newDebugSandbox = function newDebugSandbox(ns) { + return browser$1("fetch-mock:".concat(phase, ":").concat(ns)); + }; + + newDebug(); + var debug_1 = { + debug: function debug() { + debugFunc.apply(void 0, arguments); + }, + setDebugNamespace: function setDebugNamespace(str) { + namespace = str; + newDebug(); + }, + setDebugPhase: function setDebugPhase(str) { + phase = str || 'default'; + newDebug(); + }, + getDebug: function getDebug(namespace) { + return newDebugSandbox(namespace); + } + }; + + var debug = debug_1.debug, + setDebugPhase = debug_1.setDebugPhase; + + var FetchMock = {}; + + FetchMock.mock = function () { + setDebugPhase('setup'); + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + if (args.length) { + this.addRoute(args); + } + + return this._mock(); + }; + + FetchMock.addRoute = function (uncompiledRoute) { + var _this = this; + + debug('Adding route', uncompiledRoute); + var route = this.compileRoute(uncompiledRoute); + var clashes = this.routes.filter(function (_ref) { + var identifier = _ref.identifier, + method = _ref.method; + var isMatch = typeof identifier === 'function' ? identifier === route.identifier : String(identifier) === String(route.identifier); + return isMatch && (!method || !route.method || method === route.method); + }); + + if (this.getOption('overwriteRoutes', route) === false || !clashes.length) { + this._uncompiledRoutes.push(uncompiledRoute); + + return this.routes.push(route); + } + + if (this.getOption('overwriteRoutes', route) === true) { + clashes.forEach(function (clash) { + var index = _this.routes.indexOf(clash); + + _this._uncompiledRoutes.splice(index, 1, uncompiledRoute); + + _this.routes.splice(index, 1, route); + }); + return this.routes; + } + + if (clashes.length) { + throw new Error('fetch-mock: Adding route with same name or matcher as existing route. See `overwriteRoutes` option.'); + } + + this._uncompiledRoutes.push(uncompiledRoute); + + this.routes.push(route); + }; + + FetchMock._mock = function () { + if (!this.isSandbox) { + // Do this here rather than in the constructor to ensure it's scoped to the test + this.realFetch = this.realFetch || this.global.fetch; + this.global.fetch = this.fetchHandler; + } + + setDebugPhase(); + return this; + }; + + FetchMock["catch"] = function (response) { + if (this.fallbackResponse) { + console.warn('calling fetchMock.catch() twice - are you sure you want to overwrite the previous fallback response'); // eslint-disable-line + } + + this.fallbackResponse = response || 'ok'; + return this._mock(); + }; + + FetchMock.spy = function (route) { + // even though ._mock() is called by .mock() and .catch() we still need to + // call it here otherwise .getNativeFetch() won't be able to use the reference + // to .realFetch that ._mock() sets up + this._mock(); + + return route ? this.mock(route, this.getNativeFetch()) : this["catch"](this.getNativeFetch()); + }; + + var defineShorthand = function defineShorthand(methodName, underlyingMethod, shorthandOptions) { + FetchMock[methodName] = function (matcher, response, options) { + return this[underlyingMethod](matcher, response, Object.assign(options || {}, shorthandOptions)); + }; + }; + + var defineGreedyShorthand = function defineGreedyShorthand(methodName, underlyingMethod) { + FetchMock[methodName] = function (response, options) { + return this[underlyingMethod]({}, response, options); + }; + }; + + defineShorthand('sticky', 'mock', { + sticky: true + }); + defineShorthand('once', 'mock', { + repeat: 1 + }); + defineGreedyShorthand('any', 'mock'); + defineGreedyShorthand('anyOnce', 'once'); + ['get', 'post', 'put', 'delete', 'head', 'patch'].forEach(function (method) { + defineShorthand(method, 'mock', { + method: method + }); + defineShorthand("".concat(method, "Once"), 'once', { + method: method + }); + defineGreedyShorthand("".concat(method, "Any"), method); + defineGreedyShorthand("".concat(method, "AnyOnce"), "".concat(method, "Once")); + }); + + var mochaAsyncHookWorkaround = function mochaAsyncHookWorkaround(options) { + // HACK workaround for this https://github.com/mochajs/mocha/issues/4280 + // Note that it doesn't matter that we call it _before_ carrying out all + // the things resetBehavior does as everything in there is synchronous + if (typeof options === 'function') { + console.warn("Deprecated: Passing fetch-mock reset methods\ndirectly in as handlers for before/after test runner hooks.\nWrap in an arrow function instead e.g. `() => fetchMock.restore()`"); + options(); + } + }; + + var getRouteRemover = function getRouteRemover(_ref2) { + var removeStickyRoutes = _ref2.sticky; + return function (routes) { + return removeStickyRoutes ? [] : routes.filter(function (_ref3) { + var sticky = _ref3.sticky; + return sticky; + }); + }; + }; + + FetchMock.resetBehavior = function () { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + mochaAsyncHookWorkaround(options); + var removeRoutes = getRouteRemover(options); + this.routes = removeRoutes(this.routes); + this._uncompiledRoutes = removeRoutes(this._uncompiledRoutes); + + if (this.realFetch && !this.routes.length) { + this.global.fetch = this.realFetch; + this.realFetch = undefined; + } + + this.fallbackResponse = undefined; + return this; + }; + + FetchMock.resetHistory = function () { + this._calls = []; + this._holdingPromises = []; + this.routes.forEach(function (route) { + return route.reset && route.reset(); + }); + return this; + }; + + FetchMock.restore = FetchMock.reset = function (options) { + this.resetBehavior(options); + this.resetHistory(); + return this; + }; + + var setUpAndTearDown = FetchMock; + + var interopRequireDefault = createCommonjsModule(function (module) { + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + "default": obj + }; + } + + module.exports = _interopRequireDefault; + }); + + unwrapExports(interopRequireDefault); + + function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; + } + + var arrayWithHoles = _arrayWithHoles; + + function _iterableToArrayLimit(arr, i) { + if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; + } + + var iterableToArrayLimit = _iterableToArrayLimit; + + function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + + for (var i = 0, arr2 = new Array(len); i < len; i++) { + arr2[i] = arr[i]; + } + + return arr2; + } + + var arrayLikeToArray = _arrayLikeToArray; + + function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); + } + + var unsupportedIterableToArray = _unsupportedIterableToArray; + + function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + var nonIterableRest = _nonIterableRest; + + function _slicedToArray(arr, i) { + return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); + } + + var slicedToArray = _slicedToArray; + + var runtime_1 = createCommonjsModule(function (module) { + /** + * Copyright (c) 2014-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + var runtime = (function (exports) { + + var Op = Object.prototype; + var hasOwn = Op.hasOwnProperty; + var undefined$1; // More compressible than void 0. + var $Symbol = typeof Symbol === "function" ? Symbol : {}; + var iteratorSymbol = $Symbol.iterator || "@@iterator"; + var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; + var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + + function define(obj, key, value) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + return obj[key]; + } + try { + // IE 8 has a broken Object.defineProperty that only works on DOM objects. + define({}, ""); + } catch (err) { + define = function(obj, key, value) { + return obj[key] = value; + }; + } + + function wrap(innerFn, outerFn, self, tryLocsList) { + // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; + var generator = Object.create(protoGenerator.prototype); + var context = new Context(tryLocsList || []); + + // The ._invoke method unifies the implementations of the .next, + // .throw, and .return methods. + generator._invoke = makeInvokeMethod(innerFn, self, context); + + return generator; + } + exports.wrap = wrap; + + // Try/catch helper to minimize deoptimizations. Returns a completion + // record like context.tryEntries[i].completion. This interface could + // have been (and was previously) designed to take a closure to be + // invoked without arguments, but in all the cases we care about we + // already have an existing method we want to call, so there's no need + // to create a new function object. We can even get away with assuming + // the method takes exactly one argument, since that happens to be true + // in every case, so we don't have to touch the arguments object. The + // only additional allocation required is the completion record, which + // has a stable shape and so hopefully should be cheap to allocate. + function tryCatch(fn, obj, arg) { + try { + return { type: "normal", arg: fn.call(obj, arg) }; + } catch (err) { + return { type: "throw", arg: err }; + } + } + + var GenStateSuspendedStart = "suspendedStart"; + var GenStateSuspendedYield = "suspendedYield"; + var GenStateExecuting = "executing"; + var GenStateCompleted = "completed"; + + // Returning this object from the innerFn has the same effect as + // breaking out of the dispatch switch statement. + var ContinueSentinel = {}; + + // Dummy constructor functions that we use as the .constructor and + // .constructor.prototype properties for functions that return Generator + // objects. For full spec compliance, you may wish to configure your + // minifier not to mangle the names of these two functions. + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + + // This is a polyfill for %IteratorPrototype% for environments that + // don't natively support it. + var IteratorPrototype = {}; + IteratorPrototype[iteratorSymbol] = function () { + return this; + }; + + var getProto = Object.getPrototypeOf; + var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); + if (NativeIteratorPrototype && + NativeIteratorPrototype !== Op && + hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { + // This environment has a native %IteratorPrototype%; use it instead + // of the polyfill. + IteratorPrototype = NativeIteratorPrototype; + } + + var Gp = GeneratorFunctionPrototype.prototype = + Generator.prototype = Object.create(IteratorPrototype); + GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; + GeneratorFunctionPrototype.constructor = GeneratorFunction; + GeneratorFunction.displayName = define( + GeneratorFunctionPrototype, + toStringTagSymbol, + "GeneratorFunction" + ); + + // Helper for defining the .next, .throw, and .return methods of the + // Iterator interface in terms of a single ._invoke method. + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function(method) { + define(prototype, method, function(arg) { + return this._invoke(method, arg); + }); + }); + } + + exports.isGeneratorFunction = function(genFun) { + var ctor = typeof genFun === "function" && genFun.constructor; + return ctor + ? ctor === GeneratorFunction || + // For the native GeneratorFunction constructor, the best we can + // do is to check its .name property. + (ctor.displayName || ctor.name) === "GeneratorFunction" + : false; + }; + + exports.mark = function(genFun) { + if (Object.setPrototypeOf) { + Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); + } else { + genFun.__proto__ = GeneratorFunctionPrototype; + define(genFun, toStringTagSymbol, "GeneratorFunction"); + } + genFun.prototype = Object.create(Gp); + return genFun; + }; + + // Within the body of any async function, `await x` is transformed to + // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test + // `hasOwn.call(value, "__await")` to determine if the yielded value is + // meant to be awaited. + exports.awrap = function(arg) { + return { __await: arg }; + }; + + function AsyncIterator(generator, PromiseImpl) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + if (record.type === "throw") { + reject(record.arg); + } else { + var result = record.arg; + var value = result.value; + if (value && + typeof value === "object" && + hasOwn.call(value, "__await")) { + return PromiseImpl.resolve(value.__await).then(function(value) { + invoke("next", value, resolve, reject); + }, function(err) { + invoke("throw", err, resolve, reject); + }); + } + + return PromiseImpl.resolve(value).then(function(unwrapped) { + // When a yielded Promise is resolved, its final value becomes + // the .value of the Promise<{value,done}> result for the + // current iteration. + result.value = unwrapped; + resolve(result); + }, function(error) { + // If a rejected Promise was yielded, throw the rejection back + // into the async generator function so it can be handled there. + return invoke("throw", error, resolve, reject); + }); + } + } + + var previousPromise; + + function enqueue(method, arg) { + function callInvokeWithMethodAndArg() { + return new PromiseImpl(function(resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } + + return previousPromise = + // If enqueue has been called before, then we want to wait until + // all previous Promises have been resolved before calling invoke, + // so that results are always delivered in the correct order. If + // enqueue has not been called before, then it is important to + // call invoke immediately, without waiting on a callback to fire, + // so that the async generator function has the opportunity to do + // any necessary setup in a predictable way. This predictability + // is why the Promise constructor synchronously invokes its + // executor callback, and why async functions synchronously + // execute code before the first await. Since we implement simple + // async functions in terms of async generators, it is especially + // important to get this right, even though it requires care. + previousPromise ? previousPromise.then( + callInvokeWithMethodAndArg, + // Avoid propagating failures to Promises returned by later + // invocations of the iterator. + callInvokeWithMethodAndArg + ) : callInvokeWithMethodAndArg(); + } + + // Define the unified helper method that is used to implement .next, + // .throw, and .return (see defineIteratorMethods). + this._invoke = enqueue; + } + + defineIteratorMethods(AsyncIterator.prototype); + AsyncIterator.prototype[asyncIteratorSymbol] = function () { + return this; + }; + exports.AsyncIterator = AsyncIterator; + + // Note that simple async functions are implemented on top of + // AsyncIterator objects; they just return a Promise for the value of + // the final result produced by the iterator. + exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) { + if (PromiseImpl === void 0) PromiseImpl = Promise; + + var iter = new AsyncIterator( + wrap(innerFn, outerFn, self, tryLocsList), + PromiseImpl + ); + + return exports.isGeneratorFunction(outerFn) + ? iter // If outerFn is a generator, return the full iterator. + : iter.next().then(function(result) { + return result.done ? result.value : iter.next(); + }); + }; + + function makeInvokeMethod(innerFn, self, context) { + var state = GenStateSuspendedStart; + + return function invoke(method, arg) { + if (state === GenStateExecuting) { + throw new Error("Generator is already running"); + } + + if (state === GenStateCompleted) { + if (method === "throw") { + throw arg; + } + + // Be forgiving, per 25.3.3.3.3 of the spec: + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume + return doneResult(); + } + + context.method = method; + context.arg = arg; + + while (true) { + var delegate = context.delegate; + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } + + if (context.method === "next") { + // Setting context._sent for legacy support of Babel's + // function.sent implementation. + context.sent = context._sent = context.arg; + + } else if (context.method === "throw") { + if (state === GenStateSuspendedStart) { + state = GenStateCompleted; + throw context.arg; + } + + context.dispatchException(context.arg); + + } else if (context.method === "return") { + context.abrupt("return", context.arg); + } + + state = GenStateExecuting; + + var record = tryCatch(innerFn, self, context); + if (record.type === "normal") { + // If an exception is thrown from innerFn, we leave state === + // GenStateExecuting and loop back for another invocation. + state = context.done + ? GenStateCompleted + : GenStateSuspendedYield; + + if (record.arg === ContinueSentinel) { + continue; + } + + return { + value: record.arg, + done: context.done + }; + + } else if (record.type === "throw") { + state = GenStateCompleted; + // Dispatch the exception by looping back around to the + // context.dispatchException(context.arg) call above. + context.method = "throw"; + context.arg = record.arg; + } + } + }; + } + + // Call delegate.iterator[context.method](context.arg) and handle the + // result, either by returning a { value, done } result from the + // delegate iterator, or by modifying context.method and context.arg, + // setting context.delegate to null, and returning the ContinueSentinel. + function maybeInvokeDelegate(delegate, context) { + var method = delegate.iterator[context.method]; + if (method === undefined$1) { + // A .throw or .return when the delegate iterator has no .throw + // method always terminates the yield* loop. + context.delegate = null; + + if (context.method === "throw") { + // Note: ["return"] must be used for ES3 parsing compatibility. + if (delegate.iterator["return"]) { + // If the delegate iterator has a return method, give it a + // chance to clean up. + context.method = "return"; + context.arg = undefined$1; + maybeInvokeDelegate(delegate, context); + + if (context.method === "throw") { + // If maybeInvokeDelegate(context) changed context.method from + // "return" to "throw", let that override the TypeError below. + return ContinueSentinel; + } + } + + context.method = "throw"; + context.arg = new TypeError( + "The iterator does not provide a 'throw' method"); + } + + return ContinueSentinel; + } + + var record = tryCatch(method, delegate.iterator, context.arg); + + if (record.type === "throw") { + context.method = "throw"; + context.arg = record.arg; + context.delegate = null; + return ContinueSentinel; + } + + var info = record.arg; + + if (! info) { + context.method = "throw"; + context.arg = new TypeError("iterator result is not an object"); + context.delegate = null; + return ContinueSentinel; + } + + if (info.done) { + // Assign the result of the finished delegate to the temporary + // variable specified by delegate.resultName (see delegateYield). + context[delegate.resultName] = info.value; + + // Resume execution at the desired location (see delegateYield). + context.next = delegate.nextLoc; + + // If context.method was "throw" but the delegate handled the + // exception, let the outer generator proceed normally. If + // context.method was "next", forget context.arg since it has been + // "consumed" by the delegate iterator. If context.method was + // "return", allow the original .return call to continue in the + // outer generator. + if (context.method !== "return") { + context.method = "next"; + context.arg = undefined$1; + } + + } else { + // Re-yield the result returned by the delegate method. + return info; + } + + // The delegate iterator is finished, so forget it and continue with + // the outer generator. + context.delegate = null; + return ContinueSentinel; + } + + // Define Generator.prototype.{next,throw,return} in terms of the + // unified ._invoke helper method. + defineIteratorMethods(Gp); + + define(Gp, toStringTagSymbol, "Generator"); + + // A Generator should always return itself as the iterator object when the + // @@iterator function is called on it. Some browsers' implementations of the + // iterator prototype chain incorrectly implement this, causing the Generator + // object to not be returned from this call. This ensures that doesn't happen. + // See https://github.com/facebook/regenerator/issues/274 for more details. + Gp[iteratorSymbol] = function() { + return this; + }; + + Gp.toString = function() { + return "[object Generator]"; + }; + + function pushTryEntry(locs) { + var entry = { tryLoc: locs[0] }; + + if (1 in locs) { + entry.catchLoc = locs[1]; + } + + if (2 in locs) { + entry.finallyLoc = locs[2]; + entry.afterLoc = locs[3]; + } + + this.tryEntries.push(entry); + } + + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal"; + delete record.arg; + entry.completion = record; + } + + function Context(tryLocsList) { + // The root entry object (effectively a try statement without a catch + // or a finally block) gives us a place to store values thrown from + // locations where there is no enclosing try statement. + this.tryEntries = [{ tryLoc: "root" }]; + tryLocsList.forEach(pushTryEntry, this); + this.reset(true); + } + + exports.keys = function(object) { + var keys = []; + for (var key in object) { + keys.push(key); + } + keys.reverse(); + + // Rather than returning an object with a next method, we keep + // things simple and return the next function itself. + return function next() { + while (keys.length) { + var key = keys.pop(); + if (key in object) { + next.value = key; + next.done = false; + return next; + } + } + + // To avoid creating an additional object, we just hang the .value + // and .done properties off the next function object itself. This + // also ensures that the minifier will not anonymize the function. + next.done = true; + return next; + }; + }; + + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) { + return iteratorMethod.call(iterable); + } + + if (typeof iterable.next === "function") { + return iterable; + } + + if (!isNaN(iterable.length)) { + var i = -1, next = function next() { + while (++i < iterable.length) { + if (hasOwn.call(iterable, i)) { + next.value = iterable[i]; + next.done = false; + return next; + } + } + + next.value = undefined$1; + next.done = true; + + return next; + }; + + return next.next = next; + } + } + + // Return an iterator with no values. + return { next: doneResult }; + } + exports.values = values; + + function doneResult() { + return { value: undefined$1, done: true }; + } + + Context.prototype = { + constructor: Context, + + reset: function(skipTempReset) { + this.prev = 0; + this.next = 0; + // Resetting context._sent for legacy support of Babel's + // function.sent implementation. + this.sent = this._sent = undefined$1; + this.done = false; + this.delegate = null; + + this.method = "next"; + this.arg = undefined$1; + + this.tryEntries.forEach(resetTryEntry); + + if (!skipTempReset) { + for (var name in this) { + // Not sure about the optimal order of these conditions: + if (name.charAt(0) === "t" && + hasOwn.call(this, name) && + !isNaN(+name.slice(1))) { + this[name] = undefined$1; + } + } + } + }, + + stop: function() { + this.done = true; + + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; + if (rootRecord.type === "throw") { + throw rootRecord.arg; + } + + return this.rval; + }, + + dispatchException: function(exception) { + if (this.done) { + throw exception; + } + + var context = this; + function handle(loc, caught) { + record.type = "throw"; + record.arg = exception; + context.next = loc; + + if (caught) { + // If the dispatched exception was caught by a catch block, + // then let that catch block handle the exception normally. + context.method = "next"; + context.arg = undefined$1; + } + + return !! caught; + } + + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + var record = entry.completion; + + if (entry.tryLoc === "root") { + // Exception thrown outside of any try block that could handle + // it, so set the completion value of the entire function to + // throw the exception. + return handle("end"); + } + + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"); + var hasFinally = hasOwn.call(entry, "finallyLoc"); + + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } else if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else if (hasCatch) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } + + } else if (hasFinally) { + if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else { + throw new Error("try statement without catch or finally"); + } + } + } + }, + + abrupt: function(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && + hasOwn.call(entry, "finallyLoc") && + this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } + + if (finallyEntry && + (type === "break" || + type === "continue") && + finallyEntry.tryLoc <= arg && + arg <= finallyEntry.finallyLoc) { + // Ignore the finally entry if control is not jumping to a + // location outside the try/catch block. + finallyEntry = null; + } + + var record = finallyEntry ? finallyEntry.completion : {}; + record.type = type; + record.arg = arg; + + if (finallyEntry) { + this.method = "next"; + this.next = finallyEntry.finallyLoc; + return ContinueSentinel; + } + + return this.complete(record); + }, + + complete: function(record, afterLoc) { + if (record.type === "throw") { + throw record.arg; + } + + if (record.type === "break" || + record.type === "continue") { + this.next = record.arg; + } else if (record.type === "return") { + this.rval = this.arg = record.arg; + this.method = "return"; + this.next = "end"; + } else if (record.type === "normal" && afterLoc) { + this.next = afterLoc; + } + + return ContinueSentinel; + }, + + finish: function(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) { + this.complete(entry.completion, entry.afterLoc); + resetTryEntry(entry); + return ContinueSentinel; + } + } + }, + + "catch": function(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if (record.type === "throw") { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } + + // The context.catch method must only be called with a location + // argument that corresponds to a known catch block. + throw new Error("illegal catch attempt"); + }, + + delegateYield: function(iterable, resultName, nextLoc) { + this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }; + + if (this.method === "next") { + // Deliberately forget the last sent value so that we don't + // accidentally pass it on to the delegate. + this.arg = undefined$1; + } + + return ContinueSentinel; + } + }; + + // Regardless of whether this script is executing as a CommonJS module + // or not, return the runtime object so that we can declare the variable + // regeneratorRuntime in the outer scope, which allows this module to be + // injected easily by `bin/regenerator --include-runtime script.js`. + return exports; + + }( + // If this script is executing as a CommonJS module, use module.exports + // as the regeneratorRuntime namespace. Otherwise create a new empty + // object. Either way, the resulting object will be used to initialize + // the regeneratorRuntime variable at the top of this file. + module.exports + )); + + try { + regeneratorRuntime = runtime; + } catch (accidentalStrictMode) { + // This module should not be running in strict mode, so the above + // assignment should always work unless something is misconfigured. Just + // in case runtime.js accidentally runs in strict mode, we can escape + // strict mode using a global Function call. This could conceivably fail + // if a Content Security Policy forbids using Function, but in that case + // the proper solution is to fix the accidental strict mode problem. If + // you've misconfigured your bundler to force strict mode and applied a + // CSP to forbid Function, and you're not willing to fix either of those + // problems, please detail your unique predicament in a GitHub issue. + Function("r", "regeneratorRuntime = r")(runtime); + } + }); + + var regenerator = runtime_1; + + function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; + } + + if (info.done) { + resolve(value); + } else { + Promise.resolve(value).then(_next, _throw); + } + } + + function _asyncToGenerator(fn) { + return function () { + var self = this, + args = arguments; + return new Promise(function (resolve, reject) { + var gen = fn.apply(self, args); + + function _next(value) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); + } + + function _throw(err) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); + } + + _next(undefined); + }); + }; + } + + var asyncToGenerator = _asyncToGenerator; + + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + + var classCallCheck = _classCallCheck; + + function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return self; + } + + var assertThisInitialized = _assertThisInitialized; + + var setPrototypeOf = createCommonjsModule(function (module) { + function _setPrototypeOf(o, p) { + module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + + return _setPrototypeOf(o, p); + } + + module.exports = _setPrototypeOf; + }); + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + if (superClass) setPrototypeOf(subClass, superClass); + } + + var inherits = _inherits; + + var _typeof_1 = createCommonjsModule(function (module) { + function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + module.exports = _typeof = function _typeof(obj) { + return typeof obj; + }; + } else { + module.exports = _typeof = function _typeof(obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); + } + + module.exports = _typeof; + }); + + function _possibleConstructorReturn(self, call) { + if (call && (_typeof_1(call) === "object" || typeof call === "function")) { + return call; + } + + return assertThisInitialized(self); + } + + var possibleConstructorReturn = _possibleConstructorReturn; + + var getPrototypeOf = createCommonjsModule(function (module) { + function _getPrototypeOf(o) { + module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); + } + + module.exports = _getPrototypeOf; + }); + + function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf("[native code]") !== -1; + } + + var isNativeFunction = _isNativeFunction; + + function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + + try { + Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); + return true; + } catch (e) { + return false; + } + } + + var isNativeReflectConstruct = _isNativeReflectConstruct; + + var construct = createCommonjsModule(function (module) { + function _construct(Parent, args, Class) { + if (isNativeReflectConstruct()) { + module.exports = _construct = Reflect.construct; + } else { + module.exports = _construct = function _construct(Parent, args, Class) { + var a = [null]; + a.push.apply(a, args); + var Constructor = Function.bind.apply(Parent, a); + var instance = new Constructor(); + if (Class) setPrototypeOf(instance, Class.prototype); + return instance; + }; + } + + return _construct.apply(null, arguments); + } + + module.exports = _construct; + }); + + var wrapNativeSuper = createCommonjsModule(function (module) { + function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? new Map() : undefined; + + module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) { + if (Class === null || !isNativeFunction(Class)) return Class; + + if (typeof Class !== "function") { + throw new TypeError("Super expression must either be null or a function"); + } + + if (typeof _cache !== "undefined") { + if (_cache.has(Class)) return _cache.get(Class); + + _cache.set(Class, Wrapper); + } + + function Wrapper() { + return construct(Class, arguments, getPrototypeOf(this).constructor); + } + + Wrapper.prototype = Object.create(Class.prototype, { + constructor: { + value: Wrapper, + enumerable: false, + writable: true, + configurable: true + } + }); + return setPrototypeOf(Wrapper, Class); + }; + + return _wrapNativeSuper(Class); + } + + module.exports = _wrapNativeSuper; + }); + + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } + + var createClass = _createClass; + + var _typeof2 = interopRequireDefault(_typeof_1); + + var _classCallCheck2 = interopRequireDefault(classCallCheck); + + var _createClass2 = interopRequireDefault(createClass); + + var getDebug = debug_1.getDebug; + + var responseConfigProps = ['body', 'headers', 'throws', 'status', 'redirectUrl']; + + var ResponseBuilder = /*#__PURE__*/function () { + function ResponseBuilder(options) { + (0, _classCallCheck2["default"])(this, ResponseBuilder); + this.debug = getDebug('ResponseBuilder()'); + this.debug('Response builder created with options', options); + Object.assign(this, options); + } + + (0, _createClass2["default"])(ResponseBuilder, [{ + key: "exec", + value: function exec() { + this.debug('building response'); + this.normalizeResponseConfig(); + this.constructFetchOpts(); + this.constructResponseBody(); + var realResponse = new this.fetchMock.config.Response(this.body, this.options); + var proxyResponse = this.buildObservableResponse(realResponse); + return [realResponse, proxyResponse]; + } + }, { + key: "sendAsObject", + value: function sendAsObject() { + var _this = this; + + if (responseConfigProps.some(function (prop) { + return _this.responseConfig[prop]; + })) { + if (Object.keys(this.responseConfig).every(function (key) { + return responseConfigProps.includes(key); + })) { + return false; + } else { + return true; + } + } else { + return true; + } + } + }, { + key: "normalizeResponseConfig", + value: function normalizeResponseConfig() { + // If the response config looks like a status, start to generate a simple response + if (typeof this.responseConfig === 'number') { + this.debug('building response using status', this.responseConfig); + this.responseConfig = { + status: this.responseConfig + }; // If the response config is not an object, or is an object that doesn't use + // any reserved properties, assume it is meant to be the body of the response + } else if (typeof this.responseConfig === 'string' || this.sendAsObject()) { + this.debug('building text response from', this.responseConfig); + this.responseConfig = { + body: this.responseConfig + }; + } + } + }, { + key: "validateStatus", + value: function validateStatus(status) { + if (!status) { + this.debug('No status provided. Defaulting to 200'); + return 200; + } + + if (typeof status === 'number' && parseInt(status, 10) !== status && status >= 200 || status < 600) { + this.debug('Valid status provided', status); + return status; + } + + throw new TypeError("fetch-mock: Invalid status ".concat(status, " passed on response object.\nTo respond with a JSON object that has status as a property assign the object to body\ne.g. {\"body\": {\"status: \"registered\"}}")); + } + }, { + key: "constructFetchOpts", + value: function constructFetchOpts() { + this.options = this.responseConfig.options || {}; + this.options.url = this.responseConfig.redirectUrl || this.url; + this.options.status = this.validateStatus(this.responseConfig.status); + this.options.statusText = this.fetchMock.statusTextMap[String(this.options.status)]; // Set up response headers. The empty object is to cope with + // new Headers(undefined) throwing in Chrome + // https://code.google.com/p/chromium/issues/detail?id=335871 + + this.options.headers = new this.fetchMock.config.Headers(this.responseConfig.headers || {}); + } + }, { + key: "getOption", + value: function getOption(name) { + return this.fetchMock.getOption(name, this.route); + } + }, { + key: "convertToJson", + value: function convertToJson() { + // convert to json if we need to + if (this.getOption('sendAsJson') && this.responseConfig.body != null && //eslint-disable-line + (0, _typeof2["default"])(this.body) === 'object') { + this.debug('Stringifying JSON response body'); + this.body = JSON.stringify(this.body); + + if (!this.options.headers.has('Content-Type')) { + this.options.headers.set('Content-Type', 'application/json'); + } + } + } + }, { + key: "setContentLength", + value: function setContentLength() { + // add a Content-Length header if we need to + if (this.getOption('includeContentLength') && typeof this.body === 'string' && !this.options.headers.has('Content-Length')) { + this.debug('Setting content-length header:', this.body.length.toString()); + this.options.headers.set('Content-Length', this.body.length.toString()); + } + } + }, { + key: "constructResponseBody", + value: function constructResponseBody() { + // start to construct the body + this.body = this.responseConfig.body; + this.convertToJson(); + this.setContentLength(); // On the server we need to manually construct the readable stream for the + // Response object (on the client this done automatically) + + if (this.Stream) { + this.debug('Creating response stream'); + var stream = new this.Stream.Readable(); + + if (this.body != null) { + //eslint-disable-line + stream.push(this.body, 'utf-8'); + } + + stream.push(null); + this.body = stream; + } + + this.body = this.body; + } + }, { + key: "buildObservableResponse", + value: function buildObservableResponse(response) { + var _this2 = this; + + var fetchMock = this.fetchMock; + response._fmResults = {}; // Using a proxy means we can set properties that may not be writable on + // the original Response. It also means we can track the resolution of + // promises returned by res.json(), res.text() etc + + this.debug('Wrapping Response in ES proxy for observability'); + return new Proxy(response, { + get: function get(originalResponse, name) { + if (_this2.responseConfig.redirectUrl) { + if (name === 'url') { + _this2.debug('Retrieving redirect url', _this2.responseConfig.redirectUrl); + + return _this2.responseConfig.redirectUrl; + } + + if (name === 'redirected') { + _this2.debug('Retrieving redirected status', true); + + return true; + } + } + + if (typeof originalResponse[name] === 'function') { + _this2.debug('Wrapping body promises in ES proxies for observability'); + + return new Proxy(originalResponse[name], { + apply: function apply(func, thisArg, args) { + _this2.debug("Calling res.".concat(name)); + + var result = func.apply(response, args); + + if (result.then) { + fetchMock._holdingPromises.push(result["catch"](function () { + return null; + })); + + originalResponse._fmResults[name] = result; + } + + return result; + } + }); + } + + return originalResponse[name]; + } + }); + } + }]); + return ResponseBuilder; + }(); + + var responseBuilder = function (options) { + return new ResponseBuilder(options).exec(); + }; + + function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; + } + + var defineProperty = _defineProperty; + + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return arrayLikeToArray(arr); + } + + var arrayWithoutHoles = _arrayWithoutHoles; + + function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); + } + + var iterableToArray = _iterableToArray; + + function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + var nonIterableSpread = _nonIterableSpread; + + function _toConsumableArray(arr) { + return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread(); + } + + var toConsumableArray = _toConsumableArray; + + var _typeof2$1 = interopRequireDefault(_typeof_1); + + var _regenerator = interopRequireDefault(regenerator); + + var _asyncToGenerator2 = interopRequireDefault(asyncToGenerator); + + var _defineProperty2 = interopRequireDefault(defineProperty); + + var _slicedToArray2 = interopRequireDefault(slicedToArray); + + var _toConsumableArray2 = interopRequireDefault(toConsumableArray); + + var URL; // https://stackoverflow.com/a/19709846/308237 + // split, URL constructor does not support protocol-relative urls + + var absoluteUrlRX = new RegExp('^[a-z]+://', 'i'); + var protocolRelativeUrlRX = new RegExp('^//', 'i'); + + var headersToArray = function headersToArray(headers) { + // node-fetch 1 Headers + if (typeof headers.raw === 'function') { + return Object.entries(headers.raw()); + } else if (headers[Symbol.iterator]) { + return (0, _toConsumableArray2["default"])(headers); + } else { + return Object.entries(headers); + } + }; + + var zipObject = function zipObject(entries) { + return entries.reduce(function (obj, _ref) { + var _ref2 = (0, _slicedToArray2["default"])(_ref, 2), + key = _ref2[0], + val = _ref2[1]; + + return Object.assign(obj, (0, _defineProperty2["default"])({}, key, val)); + }, {}); + }; + + var normalizeUrl = function normalizeUrl(url) { + if (typeof url === 'function' || url instanceof RegExp || /^(begin|end|glob|express|path)\:/.test(url)) { + return url; + } + + if (absoluteUrlRX.test(url)) { + var u = new URL(url); + return u.href; + } else if (protocolRelativeUrlRX.test(url)) { + var _u = new URL(url, 'http://dummy'); + + return _u.href; + } else { + var _u2 = new URL(url, 'http://dummy'); + + return _u2.pathname + _u2.search; + } + }; + + var extractBody = /*#__PURE__*/function () { + var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(request) { + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + + if (!('body' in request)) { + _context.next = 3; + break; + } + + return _context.abrupt("return", request.body.toString()); + + case 3: + return _context.abrupt("return", request.clone().text()); + + case 6: + _context.prev = 6; + _context.t0 = _context["catch"](0); + + case 8: + case "end": + return _context.stop(); + } + } + }, _callee, null, [[0, 6]]); + })); + + return function extractBody(_x) { + return _ref3.apply(this, arguments); + }; + }(); + + var requestUtils = { + setUrlImplementation: function setUrlImplementation(it) { + URL = it; + }, + normalizeRequest: function normalizeRequest(url, options, Request) { + if (Request.prototype.isPrototypeOf(url)) { + var derivedOptions = { + method: url.method + }; + var body = extractBody(url); + + if (typeof body !== 'undefined') { + derivedOptions.body = body; + } + + var normalizedRequestObject = { + url: normalizeUrl(url.url), + options: Object.assign(derivedOptions, options), + request: url, + signal: options && options.signal || url.signal + }; + var headers = headersToArray(url.headers); + + if (headers.length) { + normalizedRequestObject.options.headers = zipObject(headers); + } + + return normalizedRequestObject; + } else if (typeof url === 'string' || // horrible URL object duck-typing + (0, _typeof2$1["default"])(url) === 'object' && 'href' in url) { + return { + url: normalizeUrl(url), + options: options, + signal: options && options.signal + }; + } else if ((0, _typeof2$1["default"])(url) === 'object') { + throw new TypeError('fetch-mock: Unrecognised Request object. Read the Config and Installation sections of the docs'); + } else { + throw new TypeError('fetch-mock: Invalid arguments passed to fetch'); + } + }, + normalizeUrl: normalizeUrl, + getPath: function getPath(url) { + var u = absoluteUrlRX.test(url) ? new URL(url) : new URL(url, 'http://dummy'); + return u.pathname; + }, + getQuery: function getQuery(url) { + var u = absoluteUrlRX.test(url) ? new URL(url) : new URL(url, 'http://dummy'); + return u.search ? u.search.substr(1) : ''; + }, + headers: { + normalize: function normalize(headers) { + return zipObject(headersToArray(headers)); + }, + toLowerCase: function toLowerCase(headers) { + return Object.keys(headers).reduce(function (obj, k) { + obj[k.toLowerCase()] = headers[k]; + return obj; + }, {}); + }, + equal: function equal(actualHeader, expectedHeader) { + actualHeader = Array.isArray(actualHeader) ? actualHeader : [actualHeader]; + expectedHeader = Array.isArray(expectedHeader) ? expectedHeader : [expectedHeader]; + + if (actualHeader.length !== expectedHeader.length) { + return false; + } + + return actualHeader.every(function (val, i) { + return val === expectedHeader[i]; + }); + } + } + }; + + var _slicedToArray2$1 = interopRequireDefault(slicedToArray); + + var _regenerator$1 = interopRequireDefault(regenerator); + + var _asyncToGenerator2$1 = interopRequireDefault(asyncToGenerator); + + var _classCallCheck2$1 = interopRequireDefault(classCallCheck); + + var _assertThisInitialized2 = interopRequireDefault(assertThisInitialized); + + var _inherits2 = interopRequireDefault(inherits); + + var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + + var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + + var _wrapNativeSuper2 = interopRequireDefault(wrapNativeSuper); + + function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } + + function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + + var debug$1 = debug_1.debug, + setDebugPhase$1 = debug_1.setDebugPhase, + getDebug$1 = debug_1.getDebug; + + + + + + var FetchMock$1 = {}; // see https://heycam.github.io/webidl/#aborterror for the standardised interface + // Note that this differs slightly from node-fetch + + var AbortError = /*#__PURE__*/function (_Error) { + (0, _inherits2["default"])(AbortError, _Error); + + var _super = _createSuper(AbortError); + + function AbortError() { + var _this; + + (0, _classCallCheck2$1["default"])(this, AbortError); + _this = _super.apply(this, arguments); + _this.name = 'AbortError'; + _this.message = 'The operation was aborted.'; // Do not include this class in the stacktrace + + if (Error.captureStackTrace) { + Error.captureStackTrace((0, _assertThisInitialized2["default"])(_this), _this.constructor); + } + + return _this; + } + + return AbortError; + }( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error)); // Patch native fetch to avoid "NotSupportedError:ReadableStream uploading is not supported" in Safari. + // See also https://github.com/wheresrhys/fetch-mock/issues/584 + // See also https://stackoverflow.com/a/50952018/1273406 + + + var patchNativeFetchForSafari = function patchNativeFetchForSafari(nativeFetch) { + // Try to patch fetch only on Safari + if (typeof navigator === 'undefined' || !navigator.vendor || navigator.vendor !== 'Apple Computer, Inc.') { + return nativeFetch; + } // It seems the code is working on Safari thus patch native fetch to avoid the error. + + + return /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2$1["default"])( /*#__PURE__*/_regenerator$1["default"].mark(function _callee(request) { + var method, body, cache, credentials, headers, integrity, mode, redirect, referrer, init; + return _regenerator$1["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + method = request.method; + + if (['POST', 'PUT', 'PATCH'].includes(method)) { + _context.next = 3; + break; + } + + return _context.abrupt("return", nativeFetch(request)); + + case 3: + _context.next = 5; + return request.clone().text(); + + case 5: + body = _context.sent; + cache = request.cache, credentials = request.credentials, headers = request.headers, integrity = request.integrity, mode = request.mode, redirect = request.redirect, referrer = request.referrer; + init = { + body: body, + cache: cache, + credentials: credentials, + headers: headers, + integrity: integrity, + mode: mode, + redirect: redirect, + referrer: referrer, + method: method + }; + return _context.abrupt("return", nativeFetch(request.url, init)); + + case 9: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + + return function (_x) { + return _ref.apply(this, arguments); + }; + }(); + }; + + var resolve = /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2$1["default"])( /*#__PURE__*/_regenerator$1["default"].mark(function _callee2(_ref3, url, options, request) { + var response, _ref3$responseIsFetch, responseIsFetch, debug; + + return _regenerator$1["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + response = _ref3.response, _ref3$responseIsFetch = _ref3.responseIsFetch, responseIsFetch = _ref3$responseIsFetch === void 0 ? false : _ref3$responseIsFetch; + debug = getDebug$1('resolve()'); + debug('Recursively resolving function and promise responses'); // We want to allow things like + // - function returning a Promise for a response + // - delaying (using a timeout Promise) a function's execution to generate + // a response + // Because of this we can't safely check for function before Promisey-ness, + // or vice versa. So to keep it DRY, and flexible, we keep trying until we + // have something that looks like neither Promise nor function + + case 3: + + if (!(typeof response === 'function')) { + _context2.next = 18; + break; + } + + debug(' Response is a function'); // in the case of falling back to the network we need to make sure we're using + // the original Request instance, not our normalised url + options + + if (!responseIsFetch) { + _context2.next = 14; + break; + } + + if (!request) { + _context2.next = 10; + break; + } + + debug(' -> Calling fetch with Request instance'); + return _context2.abrupt("return", response(request)); + + case 10: + debug(' -> Calling fetch with url and options'); + return _context2.abrupt("return", response(url, options)); + + case 14: + debug(' -> Calling response function'); + response = response(url, options, request); + + case 16: + _context2.next = 29; + break; + + case 18: + if (!(typeof response.then === 'function')) { + _context2.next = 26; + break; + } + + debug(' Response is a promise'); + debug(' -> Resolving promise'); + _context2.next = 23; + return response; + + case 23: + response = _context2.sent; + _context2.next = 29; + break; + + case 26: + debug(' Response is not a function or a promise'); + debug(' -> Exiting response resolution recursion'); + return _context2.abrupt("return", response); + + case 29: + _context2.next = 3; + break; + + case 31: + case "end": + return _context2.stop(); + } + } + }, _callee2); + })); + + return function resolve(_x2, _x3, _x4, _x5) { + return _ref2.apply(this, arguments); + }; + }(); + + FetchMock$1.needsAsyncBodyExtraction = function (_ref4) { + var request = _ref4.request; + return request && this.routes.some(function (_ref5) { + var usesBody = _ref5.usesBody; + return usesBody; + }); + }; + + FetchMock$1.fetchHandler = function (url, options) { + setDebugPhase$1('handle'); + var debug = getDebug$1('fetchHandler()'); + debug('fetch called with:', url, options); + var normalizedRequest = requestUtils.normalizeRequest(url, options, this.config.Request); + debug('Request normalised'); + debug(' url', normalizedRequest.url); + debug(' options', normalizedRequest.options); + debug(' request', normalizedRequest.request); + debug(' signal', normalizedRequest.signal); + + if (this.needsAsyncBodyExtraction(normalizedRequest)) { + debug('Need to wait for Body to be streamed before calling router: switching to async mode'); + return this._extractBodyThenHandle(normalizedRequest); + } + + return this._fetchHandler(normalizedRequest); + }; + + FetchMock$1._extractBodyThenHandle = /*#__PURE__*/function () { + var _ref6 = (0, _asyncToGenerator2$1["default"])( /*#__PURE__*/_regenerator$1["default"].mark(function _callee3(normalizedRequest) { + return _regenerator$1["default"].wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return normalizedRequest.options.body; + + case 2: + normalizedRequest.options.body = _context3.sent; + return _context3.abrupt("return", this._fetchHandler(normalizedRequest)); + + case 4: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); + + return function (_x6) { + return _ref6.apply(this, arguments); + }; + }(); + + FetchMock$1._fetchHandler = function (_ref7) { + var _this2 = this; + + var url = _ref7.url, + options = _ref7.options, + request = _ref7.request, + signal = _ref7.signal; + + var _this$executeRouter = this.executeRouter(url, options, request), + route = _this$executeRouter.route, + callLog = _this$executeRouter.callLog; + + this.recordCall(callLog); // this is used to power the .flush() method + + var done; + + this._holdingPromises.push(new this.config.Promise(function (res) { + return done = res; + })); // wrapped in this promise to make sure we respect custom Promise + // constructors defined by the user + + + return new this.config.Promise(function (res, rej) { + if (signal) { + debug$1('signal exists - enabling fetch abort'); + + var abort = function abort() { + debug$1('aborting fetch'); // note that DOMException is not available in node.js; + // even node-fetch uses a custom error class: + // https://github.com/bitinn/node-fetch/blob/master/src/abort-error.js + + rej(typeof DOMException !== 'undefined' ? new DOMException('The operation was aborted.', 'AbortError') : new AbortError()); + done(); + }; + + if (signal.aborted) { + debug$1('signal is already aborted - aborting the fetch'); + abort(); + } + + signal.addEventListener('abort', abort); + } + + _this2.generateResponse({ + route: route, + url: url, + options: options, + request: request, + callLog: callLog + }).then(res, rej).then(done, done).then(function () { + setDebugPhase$1(); + }); + }); + }; + + FetchMock$1.fetchHandler.isMock = true; + + FetchMock$1.executeRouter = function (url, options, request) { + var debug = getDebug$1('executeRouter()'); + var callLog = { + url: url, + options: options, + request: request, + isUnmatched: true + }; + debug("Attempting to match request to a route"); + + if (this.getOption('fallbackToNetwork') === 'always') { + debug(' Configured with fallbackToNetwork=always - passing through to fetch'); + return { + route: { + response: this.getNativeFetch(), + responseIsFetch: true + } // BUG - this callLog never used to get sent. Discovered the bug + // but can't fix outside a major release as it will potentially + // cause too much disruption + // + // callLog, + + }; + } + + var route = this.router(url, options, request); + + if (route) { + debug(' Matching route found'); + return { + route: route, + callLog: { + url: url, + options: options, + request: request, + identifier: route.identifier + } + }; + } + + if (this.getOption('warnOnFallback')) { + console.warn("Unmatched ".concat(options && options.method || 'GET', " to ").concat(url)); // eslint-disable-line + } + + if (this.fallbackResponse) { + debug(' No matching route found - using fallbackResponse'); + return { + route: { + response: this.fallbackResponse + }, + callLog: callLog + }; + } + + if (!this.getOption('fallbackToNetwork')) { + throw new Error("fetch-mock: No fallback response defined for ".concat(options && options.method || 'GET', " to ").concat(url)); + } + + debug(' Configured to fallbackToNetwork - passing through to fetch'); + return { + route: { + response: this.getNativeFetch(), + responseIsFetch: true + }, + callLog: callLog + }; + }; + + FetchMock$1.generateResponse = /*#__PURE__*/function () { + var _ref8 = (0, _asyncToGenerator2$1["default"])( /*#__PURE__*/_regenerator$1["default"].mark(function _callee4(_ref9) { + var route, url, options, request, _ref9$callLog, callLog, debug, response, _responseBuilder, _responseBuilder2, realResponse, finalResponse; + + return _regenerator$1["default"].wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + route = _ref9.route, url = _ref9.url, options = _ref9.options, request = _ref9.request, _ref9$callLog = _ref9.callLog, callLog = _ref9$callLog === void 0 ? {} : _ref9$callLog; + debug = getDebug$1('generateResponse()'); + _context4.next = 4; + return resolve(route, url, options, request); + + case 4: + response = _context4.sent; + + if (!(response["throws"] && typeof response !== 'function')) { + _context4.next = 8; + break; + } + + debug('response.throws is defined - throwing an error'); + throw response["throws"]; + + case 8: + if (!this.config.Response.prototype.isPrototypeOf(response)) { + _context4.next = 12; + break; + } + + debug('response is already a Response instance - returning it'); + callLog.response = response; + return _context4.abrupt("return", response); + + case 12: + // finally, if we need to convert config into a response, we do it + _responseBuilder = responseBuilder({ + url: url, + responseConfig: response, + fetchMock: this, + route: route + }), _responseBuilder2 = (0, _slicedToArray2$1["default"])(_responseBuilder, 2), realResponse = _responseBuilder2[0], finalResponse = _responseBuilder2[1]; + callLog.response = realResponse; + return _context4.abrupt("return", finalResponse); + + case 15: + case "end": + return _context4.stop(); + } + } + }, _callee4, this); + })); + + return function (_x7) { + return _ref8.apply(this, arguments); + }; + }(); + + FetchMock$1.router = function (url, options, request) { + var route = this.routes.find(function (route, i) { + debug$1("Trying to match route ".concat(i)); + return route.matcher(url, options, request); + }); + + if (route) { + return route; + } + }; + + FetchMock$1.getNativeFetch = function () { + var func = this.realFetch || this.isSandbox && this.config.fetch; + + if (!func) { + throw new Error('fetch-mock: Falling back to network only available on global fetch-mock, or by setting config.fetch on sandboxed fetch-mock'); + } + + return patchNativeFetchForSafari(func); + }; + + FetchMock$1.recordCall = function (obj) { + debug$1('Recording fetch call', obj); + + if (obj) { + this._calls.push(obj); + } + }; + + var fetchHandler = FetchMock$1; + + var globToRegexp = function (glob, opts) { + if (typeof glob !== 'string') { + throw new TypeError('Expected a string'); + } + + var str = String(glob); + + // The regexp we are building, as a string. + var reStr = ""; + + // Whether we are matching so called "extended" globs (like bash) and should + // support single character matching, matching ranges of characters, group + // matching, etc. + var extended = opts ? !!opts.extended : false; + + // When globstar is _false_ (default), '/foo/*' is translated a regexp like + // '^\/foo\/.*$' which will match any string beginning with '/foo/' + // When globstar is _true_, '/foo/*' is translated to regexp like + // '^\/foo\/[^/]*$' which will match any string beginning with '/foo/' BUT + // which does not have a '/' to the right of it. + // E.g. with '/foo/*' these will match: '/foo/bar', '/foo/bar.txt' but + // these will not '/foo/bar/baz', '/foo/bar/baz.txt' + // Lastely, when globstar is _true_, '/foo/**' is equivelant to '/foo/*' when + // globstar is _false_ + var globstar = opts ? !!opts.globstar : false; + + // If we are doing extended matching, this boolean is true when we are inside + // a group (eg {*.html,*.js}), and false otherwise. + var inGroup = false; + + // RegExp flags (eg "i" ) to pass in to RegExp constructor. + var flags = opts && typeof( opts.flags ) === "string" ? opts.flags : ""; + + var c; + for (var i = 0, len = str.length; i < len; i++) { + c = str[i]; + + switch (c) { + case "/": + case "$": + case "^": + case "+": + case ".": + case "(": + case ")": + case "=": + case "!": + case "|": + reStr += "\\" + c; + break; + + case "?": + if (extended) { + reStr += "."; + break; + } + + case "[": + case "]": + if (extended) { + reStr += c; + break; + } + + case "{": + if (extended) { + inGroup = true; + reStr += "("; + break; + } + + case "}": + if (extended) { + inGroup = false; + reStr += ")"; + break; + } + + case ",": + if (inGroup) { + reStr += "|"; + break; + } + reStr += "\\" + c; + break; + + case "*": + // Move over all consecutive "*"'s. + // Also store the previous and next characters + var prevChar = str[i - 1]; + var starCount = 1; + while(str[i + 1] === "*") { + starCount++; + i++; + } + var nextChar = str[i + 1]; + + if (!globstar) { + // globstar is disabled, so treat any number of "*" as one + reStr += ".*"; + } else { + // globstar is enabled, so determine if this is a globstar segment + var isGlobstar = starCount > 1 // multiple "*"'s + && (prevChar === "/" || prevChar === undefined) // from the start of the segment + && (nextChar === "/" || nextChar === undefined); // to the end of the segment + + if (isGlobstar) { + // it's a globstar, so match zero or more path segments + reStr += "((?:[^/]*(?:\/|$))*)"; + i++; // move over the "/" + } else { + // it's not a globstar, so only match one path segment + reStr += "([^/]*)"; + } + } + break; + + default: + reStr += c; + } + } + + // When regexp 'g' flag is specified don't + // constrain the regular expression with ^ & $ + if (!flags || !~flags.indexOf('g')) { + reStr = "^" + reStr + "$"; + } + + return new RegExp(reStr, flags); + }; + + /** + * Expose `pathToRegexp`. + */ + var pathToRegexp_1 = pathToRegexp; + var parse_1 = parse$1; + var compile_1 = compile; + var tokensToFunction_1 = tokensToFunction; + var tokensToRegExp_1 = tokensToRegExp; + + /** + * Default configs. + */ + var DEFAULT_DELIMITER = '/'; + var DEFAULT_DELIMITERS = './'; + + /** + * The main path matching regexp utility. + * + * @type {RegExp} + */ + var PATH_REGEXP = new RegExp([ + // Match escaped characters that would otherwise appear in future matches. + // This allows the user to escape special characters that won't transform. + '(\\\\.)', + // Match Express-style parameters and un-named parameters with a prefix + // and optional suffixes. Matches appear as: + // + // ":test(\\d+)?" => ["test", "\d+", undefined, "?"] + // "(\\d+)" => [undefined, undefined, "\d+", undefined] + '(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?' + ].join('|'), 'g'); + + /** + * Parse a string for the raw tokens. + * + * @param {string} str + * @param {Object=} options + * @return {!Array} + */ + function parse$1 (str, options) { + var tokens = []; + var key = 0; + var index = 0; + var path = ''; + var defaultDelimiter = (options && options.delimiter) || DEFAULT_DELIMITER; + var delimiters = (options && options.delimiters) || DEFAULT_DELIMITERS; + var pathEscaped = false; + var res; + + while ((res = PATH_REGEXP.exec(str)) !== null) { + var m = res[0]; + var escaped = res[1]; + var offset = res.index; + path += str.slice(index, offset); + index = offset + m.length; + + // Ignore already escaped sequences. + if (escaped) { + path += escaped[1]; + pathEscaped = true; + continue + } + + var prev = ''; + var next = str[index]; + var name = res[2]; + var capture = res[3]; + var group = res[4]; + var modifier = res[5]; + + if (!pathEscaped && path.length) { + var k = path.length - 1; + + if (delimiters.indexOf(path[k]) > -1) { + prev = path[k]; + path = path.slice(0, k); + } + } + + // Push the current path onto the tokens. + if (path) { + tokens.push(path); + path = ''; + pathEscaped = false; + } + + var partial = prev !== '' && next !== undefined && next !== prev; + var repeat = modifier === '+' || modifier === '*'; + var optional = modifier === '?' || modifier === '*'; + var delimiter = prev || defaultDelimiter; + var pattern = capture || group; + + tokens.push({ + name: name || key++, + prefix: prev, + delimiter: delimiter, + optional: optional, + repeat: repeat, + partial: partial, + pattern: pattern ? escapeGroup(pattern) : '[^' + escapeString(delimiter) + ']+?' + }); + } + + // Push any remaining characters. + if (path || index < str.length) { + tokens.push(path + str.substr(index)); + } + + return tokens + } + + /** + * Compile a string to a template function for the path. + * + * @param {string} str + * @param {Object=} options + * @return {!function(Object=, Object=)} + */ + function compile (str, options) { + return tokensToFunction(parse$1(str, options)) + } + + /** + * Expose a method for transforming tokens into the path function. + */ + function tokensToFunction (tokens) { + // Compile all the tokens into regexps. + var matches = new Array(tokens.length); + + // Compile all the patterns before compilation. + for (var i = 0; i < tokens.length; i++) { + if (typeof tokens[i] === 'object') { + matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$'); + } + } + + return function (data, options) { + var path = ''; + var encode = (options && options.encode) || encodeURIComponent; + + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + + if (typeof token === 'string') { + path += token; + continue + } + + var value = data ? data[token.name] : undefined; + var segment; + + if (Array.isArray(value)) { + if (!token.repeat) { + throw new TypeError('Expected "' + token.name + '" to not repeat, but got array') + } + + if (value.length === 0) { + if (token.optional) continue + + throw new TypeError('Expected "' + token.name + '" to not be empty') + } + + for (var j = 0; j < value.length; j++) { + segment = encode(value[j], token); + + if (!matches[i].test(segment)) { + throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '"') + } + + path += (j === 0 ? token.prefix : token.delimiter) + segment; + } + + continue + } + + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + segment = encode(String(value), token); + + if (!matches[i].test(segment)) { + throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but got "' + segment + '"') + } + + path += token.prefix + segment; + continue + } + + if (token.optional) { + // Prepend partial segment prefixes. + if (token.partial) path += token.prefix; + + continue + } + + throw new TypeError('Expected "' + token.name + '" to be ' + (token.repeat ? 'an array' : 'a string')) + } + + return path + } + } + + /** + * Escape a regular expression string. + * + * @param {string} str + * @return {string} + */ + function escapeString (str) { + return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1') + } + + /** + * Escape the capturing group by escaping special characters and meaning. + * + * @param {string} group + * @return {string} + */ + function escapeGroup (group) { + return group.replace(/([=!:$/()])/g, '\\$1') + } + + /** + * Get the flags for a regexp from the options. + * + * @param {Object} options + * @return {string} + */ + function flags (options) { + return options && options.sensitive ? '' : 'i' + } + + /** + * Pull out keys from a regexp. + * + * @param {!RegExp} path + * @param {Array=} keys + * @return {!RegExp} + */ + function regexpToRegexp (path, keys) { + if (!keys) return path + + // Use a negative lookahead to match only capturing groups. + var groups = path.source.match(/\((?!\?)/g); + + if (groups) { + for (var i = 0; i < groups.length; i++) { + keys.push({ + name: i, + prefix: null, + delimiter: null, + optional: false, + repeat: false, + partial: false, + pattern: null + }); + } + } + + return path + } + + /** + * Transform an array into a regexp. + * + * @param {!Array} path + * @param {Array=} keys + * @param {Object=} options + * @return {!RegExp} + */ + function arrayToRegexp (path, keys, options) { + var parts = []; + + for (var i = 0; i < path.length; i++) { + parts.push(pathToRegexp(path[i], keys, options).source); + } + + return new RegExp('(?:' + parts.join('|') + ')', flags(options)) + } + + /** + * Create a path regexp from string input. + * + * @param {string} path + * @param {Array=} keys + * @param {Object=} options + * @return {!RegExp} + */ + function stringToRegexp (path, keys, options) { + return tokensToRegExp(parse$1(path, options), keys, options) + } + + /** + * Expose a function for taking tokens and returning a RegExp. + * + * @param {!Array} tokens + * @param {Array=} keys + * @param {Object=} options + * @return {!RegExp} + */ + function tokensToRegExp (tokens, keys, options) { + options = options || {}; + + var strict = options.strict; + var start = options.start !== false; + var end = options.end !== false; + var delimiter = escapeString(options.delimiter || DEFAULT_DELIMITER); + var delimiters = options.delimiters || DEFAULT_DELIMITERS; + var endsWith = [].concat(options.endsWith || []).map(escapeString).concat('$').join('|'); + var route = start ? '^' : ''; + var isEndDelimited = tokens.length === 0; + + // Iterate over the tokens and create our regexp string. + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + + if (typeof token === 'string') { + route += escapeString(token); + isEndDelimited = i === tokens.length - 1 && delimiters.indexOf(token[token.length - 1]) > -1; + } else { + var capture = token.repeat + ? '(?:' + token.pattern + ')(?:' + escapeString(token.delimiter) + '(?:' + token.pattern + '))*' + : token.pattern; + + if (keys) keys.push(token); + + if (token.optional) { + if (token.partial) { + route += escapeString(token.prefix) + '(' + capture + ')?'; + } else { + route += '(?:' + escapeString(token.prefix) + '(' + capture + '))?'; + } + } else { + route += escapeString(token.prefix) + '(' + capture + ')'; + } + } + } + + if (end) { + if (!strict) route += '(?:' + delimiter + ')?'; + + route += endsWith === '$' ? '$' : '(?=' + endsWith + ')'; + } else { + if (!strict) route += '(?:' + delimiter + '(?=' + endsWith + '))?'; + if (!isEndDelimited) route += '(?=' + delimiter + '|' + endsWith + ')'; + } + + return new RegExp(route, flags(options)) + } + + /** + * Normalize the given path string, returning a regular expression. + * + * An empty array can be passed in for the keys, which will hold the + * placeholder key descriptions. For example, using `/user/:id`, `keys` will + * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`. + * + * @param {(string|RegExp|Array)} path + * @param {Array=} keys + * @param {Object=} options + * @return {!RegExp} + */ + function pathToRegexp (path, keys, options) { + if (path instanceof RegExp) { + return regexpToRegexp(path, keys) + } + + if (Array.isArray(path)) { + return arrayToRegexp(/** @type {!Array} */ (path), keys, options) + } + + return stringToRegexp(/** @type {string} */ (path), keys, options) + } + pathToRegexp_1.parse = parse_1; + pathToRegexp_1.compile = compile_1; + pathToRegexp_1.tokensToFunction = tokensToFunction_1; + pathToRegexp_1.tokensToRegExp = tokensToRegExp_1; + + // Copyright Joyent, Inc. and other Node contributors. + + // If obj.hasOwnProperty has been overridden, then calling + // obj.hasOwnProperty(prop) will break. + // See: https://github.com/joyent/node/issues/1707 + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var decode = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (Array.isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; + }; + + // Copyright Joyent, Inc. and other Node contributors. + + var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } + }; + + var encode = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return Object.keys(obj).map(function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (Array.isArray(obj[k])) { + return obj[k].map(function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); + }; + + var querystring = createCommonjsModule(function (module, exports) { + + exports.decode = exports.parse = decode; + exports.encode = exports.stringify = encode; + }); + var querystring_1 = querystring.decode; + var querystring_2 = querystring.parse; + var querystring_3 = querystring.encode; + var querystring_4 = querystring.stringify; + + var isSubset_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, '__esModule', { + value: true + }); + /** + * Check if an object is contained within another object. + * + * Returns `true` if: + * - all enumerable keys of *subset* are also enumerable in *superset*, and + * - every value assigned to an enumerable key of *subset* strictly equals + * the value assigned to the same key of *superset* – or is a subset of it. + * + * @param {Object} superset + * @param {Object} subset + * + * @returns {Boolean} + * + * @module is-subset + * @function default + * @alias isSubset + */ + var isSubset = (function (_isSubset) { + function isSubset(_x, _x2) { + return _isSubset.apply(this, arguments); + } + + isSubset.toString = function () { + return _isSubset.toString(); + }; + + return isSubset; + })(function (superset, subset) { + if (typeof superset !== 'object' || superset === null || (typeof subset !== 'object' || subset === null)) return false; + + return Object.keys(subset).every(function (key) { + if (!superset.propertyIsEnumerable(key)) return false; + + var subsetItem = subset[key]; + var supersetItem = superset[key]; + if (typeof subsetItem === 'object' && subsetItem !== null ? !isSubset(supersetItem, subsetItem) : supersetItem !== subsetItem) return false; + + return true; + }); + }); + + exports['default'] = isSubset; + module.exports = exports['default']; + }); + + unwrapExports(isSubset_1); + + var lodash_isequal = createCommonjsModule(function (module, exports) { + /** + * Lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright JS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + + /** Used as references for various `Number` constants. */ + var MAX_SAFE_INTEGER = 9007199254740991; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + nullTag = '[object Null]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + undefinedTag = '[object Undefined]', + weakMapTag = '[object WeakMap]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); + + /** Detect free variable `exports`. */ + var freeExports = exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process; + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); + + /* Node.js helper references. */ + var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key); + } + + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } + + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + + /** Used to detect overreaching core-js shims. */ + var coreJsData = root['__core-js_shared__']; + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var nativeObjectToString = objectProto.toString; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** Built-in value references. */ + var Buffer = moduleExports ? root.Buffer : undefined, + Symbol = root.Symbol, + Uint8Array = root.Uint8Array, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + symToStringTag = Symbol ? Symbol.toStringTag : undefined; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeKeys = overArg(Object.keys, Object); + + /* Built-in method references that are verified to be native. */ + var DataView = getNative(root, 'DataView'), + Map = getNative(root, 'Map'), + Promise = getNative(root, 'Promise'), + Set = getNative(root, 'Set'), + WeakMap = getNative(root, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; + + /** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + + /** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; + } + + /** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); + } + + /** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + + /** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + + /** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; + } + + /** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + + /** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; + } + + /** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + + /** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + + /** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + /** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } + } + + /** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; + } + + /** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ + function setCacheHas(value) { + return this.__data__.has(value); + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + /** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + + /** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; + } + + /** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; + } + + /** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function stackGet(key) { + return this.__data__.get(key); + } + + /** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function stackHas(key) { + return this.__data__.has(key); + } + + /** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; + } + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + + /** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } + + /** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); + } + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; + } + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other); + + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); + } + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; + } + + /** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); + } + + /** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; + } + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } + + /** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; + } + + /** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); + }; + + /** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; + } + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); + } + + /** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; + } + + /** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + function objectToString(value) { + return nativeObjectToString.call(value); + } + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse; + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other); + } + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == 'object'; + } + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + + /** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ + function stubArray() { + return []; + } + + /** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ + function stubFalse() { + return false; + } + + module.exports = isEqual; + }); + + var _defineProperty2$1 = interopRequireDefault(defineProperty); + + var debug$2 = debug_1.debug; + + + + + + + + + + var headerUtils = requestUtils.headers, + getPath = requestUtils.getPath, + getQuery = requestUtils.getQuery, + normalizeUrl$1 = requestUtils.normalizeUrl; + + + + var debuggableUrlFunc = function debuggableUrlFunc(func) { + return function (url) { + debug$2('Actual url:', url); + return func(url); + }; + }; + + var stringMatchers = { + begin: function begin(targetString) { + return debuggableUrlFunc(function (url) { + return url.indexOf(targetString) === 0; + }); + }, + end: function end(targetString) { + return debuggableUrlFunc(function (url) { + return url.substr(-targetString.length) === targetString; + }); + }, + glob: function glob(targetString) { + var urlRX = globToRegexp(targetString); + + return debuggableUrlFunc(function (url) { + return urlRX.test(url); + }); + }, + express: function express(targetString) { + var urlRX = pathToRegexp_1(targetString); + return debuggableUrlFunc(function (url) { + return urlRX.test(getPath(url)); + }); + }, + path: function path(targetString) { + return debuggableUrlFunc(function (url) { + return getPath(url) === targetString; + }); + } + }; + + var getHeaderMatcher = function getHeaderMatcher(_ref) { + var expectedHeaders = _ref.headers; + debug$2('Generating header matcher'); + + if (!expectedHeaders) { + debug$2(' No header expectations defined - skipping'); + return; + } + + var expectation = headerUtils.toLowerCase(expectedHeaders); + debug$2(' Expected headers:', expectation); + return function (url, _ref2) { + var _ref2$headers = _ref2.headers, + headers = _ref2$headers === void 0 ? {} : _ref2$headers; + debug$2('Attempting to match headers'); + var lowerCaseHeaders = headerUtils.toLowerCase(headerUtils.normalize(headers)); + debug$2(' Expected headers:', expectation); + debug$2(' Actual headers:', lowerCaseHeaders); + return Object.keys(expectation).every(function (headerName) { + return headerUtils.equal(lowerCaseHeaders[headerName], expectation[headerName]); + }); + }; + }; + + var getMethodMatcher = function getMethodMatcher(_ref3) { + var expectedMethod = _ref3.method; + debug$2('Generating method matcher'); + + if (!expectedMethod) { + debug$2(' No method expectations defined - skipping'); + return; + } + + debug$2(' Expected method:', expectedMethod); + return function (url, _ref4) { + var method = _ref4.method; + debug$2('Attempting to match method'); + var actualMethod = method ? method.toLowerCase() : 'get'; + debug$2(' Expected method:', expectedMethod); + debug$2(' Actual method:', actualMethod); + return expectedMethod === actualMethod; + }; + }; + + var getQueryStringMatcher = function getQueryStringMatcher(_ref5) { + var passedQuery = _ref5.query; + debug$2('Generating query parameters matcher'); + + if (!passedQuery) { + debug$2(' No query parameters expectations defined - skipping'); + return; + } + + var expectedQuery = querystring.parse(querystring.stringify(passedQuery)); + debug$2(' Expected query parameters:', passedQuery); + var keys = Object.keys(expectedQuery); + return function (url) { + debug$2('Attempting to match query parameters'); + var query = querystring.parse(getQuery(url)); + debug$2(' Expected query parameters:', expectedQuery); + debug$2(' Actual query parameters:', query); + return keys.every(function (key) { + if (Array.isArray(query[key])) { + if (!Array.isArray(expectedQuery[key])) { + return false; + } else { + return lodash_isequal(query[key].sort(), expectedQuery[key].sort()); + } + } + + return query[key] === expectedQuery[key]; + }); + }; + }; + + var getParamsMatcher = function getParamsMatcher(_ref6) { + var expectedParams = _ref6.params, + matcherUrl = _ref6.url; + debug$2('Generating path parameters matcher'); + + if (!expectedParams) { + debug$2(' No path parameters expectations defined - skipping'); + return; + } + + if (!/express:/.test(matcherUrl)) { + throw new Error('fetch-mock: matching on params is only possible when using an express: matcher'); + } + + debug$2(' Expected path parameters:', expectedParams); + var expectedKeys = Object.keys(expectedParams); + var keys = []; + var re = pathToRegexp_1(matcherUrl.replace(/^express:/, ''), keys); + return function (url) { + debug$2('Attempting to match path parameters'); + var vals = re.exec(getPath(url)) || []; + vals.shift(); + var params = keys.reduce(function (map, _ref7, i) { + var name = _ref7.name; + return vals[i] ? Object.assign(map, (0, _defineProperty2$1["default"])({}, name, vals[i])) : map; + }, {}); + debug$2(' Expected path parameters:', expectedParams); + debug$2(' Actual path parameters:', params); + return expectedKeys.every(function (key) { + return params[key] === expectedParams[key]; + }); + }; + }; + + var getBodyMatcher = function getBodyMatcher(route, fetchMock) { + var matchPartialBody = fetchMock.getOption('matchPartialBody', route); + var expectedBody = route.body; + debug$2('Generating body matcher'); + return function (url, _ref8) { + var body = _ref8.body, + _ref8$method = _ref8.method, + method = _ref8$method === void 0 ? 'get' : _ref8$method; + debug$2('Attempting to match body'); + + if (method.toLowerCase() === 'get') { + debug$2(' GET request - skip matching body'); // GET requests don’t send a body so the body matcher should be ignored for them + + return true; + } + + var sentBody = body; + + try { + debug$2(' Parsing request body as JSON'); + sentBody = JSON.parse(body); + } catch (err) { + debug$2(' Failed to parse request body as JSON', err); + } + + debug$2('Expected body:', expectedBody); + debug$2('Actual body:', sentBody); + + if (matchPartialBody) { + debug$2('matchPartialBody is true - checking for partial match only'); + } + + return sentBody && (matchPartialBody ? isSubset_1(sentBody, expectedBody) : lodash_isequal(sentBody, expectedBody)); + }; + }; + + var getFullUrlMatcher = function getFullUrlMatcher(route, matcherUrl, query) { + // if none of the special syntaxes apply, it's just a simple string match + // but we have to be careful to normalize the url we check and the name + // of the route to allow for e.g. http://it.at.there being indistinguishable + // from http://it.at.there/ once we start generating Request/Url objects + debug$2(' Matching using full url', matcherUrl); + var expectedUrl = normalizeUrl$1(matcherUrl); + debug$2(' Normalised url to:', matcherUrl); + + if (route.identifier === matcherUrl) { + debug$2(' Updating route identifier to match normalized url:', matcherUrl); + route.identifier = expectedUrl; + } + + return function (matcherUrl) { + debug$2('Expected url:', expectedUrl); + debug$2('Actual url:', matcherUrl); + + if (query && expectedUrl.indexOf('?')) { + debug$2('Ignoring query string when matching url'); + return matcherUrl.indexOf(expectedUrl) === 0; + } + + return normalizeUrl$1(matcherUrl) === expectedUrl; + }; + }; + + var getFunctionMatcher = function getFunctionMatcher(_ref9) { + var functionMatcher = _ref9.functionMatcher; + debug$2('Detected user defined function matcher', functionMatcher); + return function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + debug$2('Calling function matcher with arguments', args); + return functionMatcher.apply(void 0, args); + }; + }; + + var getUrlMatcher = function getUrlMatcher(route) { + debug$2('Generating url matcher'); + var matcherUrl = route.url, + query = route.query; + + if (matcherUrl === '*') { + debug$2(' Using universal * rule to match any url'); + return function () { + return true; + }; + } + + if (matcherUrl instanceof RegExp) { + debug$2(' Using regular expression to match url:', matcherUrl); + return function (url) { + return matcherUrl.test(url); + }; + } + + if (matcherUrl.href) { + debug$2(" Using URL object to match url", matcherUrl); + return getFullUrlMatcher(route, matcherUrl.href, query); + } + + for (var shorthand in stringMatchers) { + if (matcherUrl.indexOf(shorthand + ':') === 0) { + debug$2(" Using ".concat(shorthand, ": pattern to match url"), matcherUrl); + var urlFragment = matcherUrl.replace(new RegExp("^".concat(shorthand, ":")), ''); + return stringMatchers[shorthand](urlFragment); + } + } + + return getFullUrlMatcher(route, matcherUrl, query); + }; + + var matchers = [{ + name: 'query', + matcher: getQueryStringMatcher + }, { + name: 'method', + matcher: getMethodMatcher + }, { + name: 'headers', + matcher: getHeaderMatcher + }, { + name: 'params', + matcher: getParamsMatcher + }, { + name: 'body', + matcher: getBodyMatcher, + usesBody: true + }, { + name: 'functionMatcher', + matcher: getFunctionMatcher + }, { + name: 'url', + matcher: getUrlMatcher + }]; + + var _slicedToArray2$2 = interopRequireDefault(slicedToArray); + + var _classCallCheck2$2 = interopRequireDefault(classCallCheck); + + var _createClass2$1 = interopRequireDefault(createClass); + + var _typeof2$2 = interopRequireDefault(_typeof_1); + + + + var debug$3 = debug_1.debug, + setDebugNamespace = debug_1.setDebugNamespace, + getDebug$2 = debug_1.getDebug; + + var isUrlMatcher = function isUrlMatcher(matcher) { + return matcher instanceof RegExp || typeof matcher === 'string' || (0, _typeof2$2["default"])(matcher) === 'object' && 'href' in matcher; + }; + + var isFunctionMatcher = function isFunctionMatcher(matcher) { + return typeof matcher === 'function'; + }; + + var Route = /*#__PURE__*/function () { + function Route(args, fetchMock) { + (0, _classCallCheck2$2["default"])(this, Route); + this.fetchMock = fetchMock; + var debug = getDebug$2('compileRoute()'); + debug('Compiling route'); + this.init(args); + this.sanitize(); + this.validate(); + this.generateMatcher(); + this.limit(); + this.delayResponse(); + } + + (0, _createClass2$1["default"])(Route, [{ + key: "validate", + value: function validate() { + var _this = this; + + if (!('response' in this)) { + throw new Error('fetch-mock: Each route must define a response'); + } + + if (!Route.registeredMatchers.some(function (_ref) { + var name = _ref.name; + return name in _this; + })) { + throw new Error("fetch-mock: Each route must specify some criteria for matching calls to fetch. To match all calls use '*'"); + } + } + }, { + key: "init", + value: function init(args) { + var _args = (0, _slicedToArray2$2["default"])(args, 3), + matcher = _args[0], + response = _args[1], + _args$ = _args[2], + options = _args$ === void 0 ? {} : _args$; + + var routeConfig = {}; + + if (isUrlMatcher(matcher) || isFunctionMatcher(matcher)) { + routeConfig.matcher = matcher; + } else { + Object.assign(routeConfig, matcher); + } + + if (typeof response !== 'undefined') { + routeConfig.response = response; + } + + Object.assign(routeConfig, options); + Object.assign(this, routeConfig); + } + }, { + key: "sanitize", + value: function sanitize() { + var debug = getDebug$2('sanitize()'); + debug('Sanitizing route properties'); + + if (this.method) { + debug("Converting method ".concat(this.method, " to lower case")); + this.method = this.method.toLowerCase(); + } + + if (isUrlMatcher(this.matcher)) { + debug('Mock uses a url matcher', this.matcher); + this.url = this.matcher; + delete this.matcher; + } + + this.functionMatcher = this.matcher || this.functionMatcher; + debug('Setting route.identifier...'); + debug(" route.name is ".concat(this.name)); + debug(" route.url is ".concat(this.url)); + debug(" route.functionMatcher is ".concat(this.functionMatcher)); + this.identifier = this.name || this.url || this.functionMatcher; + debug(" -> route.identifier set to ".concat(this.identifier)); + } + }, { + key: "generateMatcher", + value: function generateMatcher() { + var _this2 = this; + + setDebugNamespace('generateMatcher()'); + debug$3('Compiling matcher for route'); + var activeMatchers = Route.registeredMatchers.map(function (_ref2) { + var name = _ref2.name, + matcher = _ref2.matcher, + usesBody = _ref2.usesBody; + return _this2[name] && { + matcher: matcher(_this2, _this2.fetchMock), + usesBody: usesBody + }; + }).filter(function (matcher) { + return Boolean(matcher); + }); + this.usesBody = activeMatchers.some(function (_ref3) { + var usesBody = _ref3.usesBody; + return usesBody; + }); + debug$3('Compiled matcher for route'); + setDebugNamespace(); + + this.matcher = function (url) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var request = arguments.length > 2 ? arguments[2] : undefined; + return activeMatchers.every(function (_ref4) { + var matcher = _ref4.matcher; + return matcher(url, options, request); + }); + }; + } + }, { + key: "limit", + value: function limit() { + var _this3 = this; + + var debug = getDebug$2('limit()'); + debug('Limiting number of requests to handle by route'); + + if (!this.repeat) { + debug(' No `repeat` value set on route. Will match any number of requests'); + return; + } + + debug(" Route set to repeat ".concat(this.repeat, " times")); + var matcher = this.matcher; + var timesLeft = this.repeat; + + this.matcher = function (url, options) { + var match = timesLeft && matcher(url, options); + + if (match) { + timesLeft--; + return true; + } + }; + + this.reset = function () { + return timesLeft = _this3.repeat; + }; + } + }, { + key: "delayResponse", + value: function delayResponse() { + var _this4 = this; + + var debug = getDebug$2('delayResponse()'); + debug("Applying response delay settings"); + + if (this.delay) { + debug(" Wrapping response in delay of ".concat(this.delay, " miliseconds")); + var response = this.response; + + this.response = function () { + debug("Delaying response by ".concat(_this4.delay, " miliseconds")); + return new Promise(function (res) { + return setTimeout(function () { + return res(response); + }, _this4.delay); + }); + }; + } else { + debug(" No delay set on route. Will respond 'immediately' (but asynchronously)"); + } + } + }], [{ + key: "addMatcher", + value: function addMatcher(matcher) { + Route.registeredMatchers.push(matcher); + } + }]); + return Route; + }(); + + Route.registeredMatchers = []; + matchers.forEach(Route.addMatcher); + var Route_1 = Route; + + var _regenerator$2 = interopRequireDefault(regenerator); + + var _asyncToGenerator2$2 = interopRequireDefault(asyncToGenerator); + + var _slicedToArray2$3 = interopRequireDefault(slicedToArray); + + var _toConsumableArray2$1 = interopRequireDefault(toConsumableArray); + + var setDebugPhase$2 = debug_1.setDebugPhase, + setDebugNamespace$1 = debug_1.setDebugNamespace, + debug$4 = debug_1.debug; + + var normalizeUrl$2 = requestUtils.normalizeUrl; + + + + var FetchMock$2 = {}; + + var isName = function isName(nameOrMatcher) { + return typeof nameOrMatcher === 'string' && /^[\da-zA-Z\-]+$/.test(nameOrMatcher); + }; + + var filterCallsWithMatcher = function filterCallsWithMatcher(matcher) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var calls = arguments.length > 2 ? arguments[2] : undefined; + + var _Route = new Route_1([Object.assign({ + matcher: matcher, + response: 'ok' + }, options)], this); + + matcher = _Route.matcher; + return calls.filter(function (_ref) { + var url = _ref.url, + options = _ref.options; + return matcher(normalizeUrl$2(url), options); + }); + }; + + var formatDebug = function formatDebug(func) { + return function () { + setDebugPhase$2('inspect'); + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var result = func.call.apply(func, [this].concat(args)); + setDebugPhase$2(); + return result; + }; + }; + + var callObjToArray = function callObjToArray(obj) { + if (!obj) { + return undefined; + } + + var url = obj.url, + options = obj.options, + request = obj.request, + identifier = obj.identifier, + isUnmatched = obj.isUnmatched, + response = obj.response; + var arr = [url, options]; + arr.request = request; + arr.identifier = identifier; + arr.isUnmatched = isUnmatched; + arr.response = response; + return arr; + }; + + FetchMock$2.filterCalls = function (nameOrMatcher, options) { + debug$4('Filtering fetch calls'); + var calls = this._calls; + var matcher = '*'; + + if ([true, 'matched'].includes(nameOrMatcher)) { + debug$4("Filter provided is ".concat(nameOrMatcher, ". Returning matched calls only")); + calls = calls.filter(function (_ref2) { + var isUnmatched = _ref2.isUnmatched; + return !isUnmatched; + }); + } else if ([false, 'unmatched'].includes(nameOrMatcher)) { + debug$4("Filter provided is ".concat(nameOrMatcher, ". Returning unmatched calls only")); + calls = calls.filter(function (_ref3) { + var isUnmatched = _ref3.isUnmatched; + return isUnmatched; + }); + } else if (typeof nameOrMatcher === 'undefined') { + debug$4("Filter provided is undefined. Returning all calls"); + calls = calls; + } else if (isName(nameOrMatcher)) { + debug$4("Filter provided, looks like the name of a named route. Returning only calls handled by that route"); + calls = calls.filter(function (_ref4) { + var identifier = _ref4.identifier; + return identifier === nameOrMatcher; + }); + } else { + matcher = nameOrMatcher === '*' ? '*' : normalizeUrl$2(nameOrMatcher); + + if (this.routes.some(function (_ref5) { + var identifier = _ref5.identifier; + return identifier === matcher; + })) { + debug$4("Filter provided, ".concat(nameOrMatcher, ", identifies a route. Returning only calls handled by that route")); + calls = calls.filter(function (call) { + return call.identifier === matcher; + }); + } + } + + if ((options || matcher !== '*') && calls.length) { + if (typeof options === 'string') { + options = { + method: options + }; + } + + debug$4('Compiling filter and options to route in order to filter all calls', nameOrMatcher); + calls = filterCallsWithMatcher.call(this, matcher, options, calls); + } + + debug$4("Retrieved ".concat(calls.length, " calls")); + return calls.map(callObjToArray); + }; + + FetchMock$2.calls = formatDebug(function (nameOrMatcher, options) { + debug$4('retrieving matching calls'); + return this.filterCalls(nameOrMatcher, options); + }); + FetchMock$2.lastCall = formatDebug(function (nameOrMatcher, options) { + debug$4('retrieving last matching call'); + return (0, _toConsumableArray2$1["default"])(this.filterCalls(nameOrMatcher, options)).pop(); + }); + FetchMock$2.lastUrl = formatDebug(function (nameOrMatcher, options) { + debug$4('retrieving url of last matching call'); + return (this.lastCall(nameOrMatcher, options) || [])[0]; + }); + FetchMock$2.lastOptions = formatDebug(function (nameOrMatcher, options) { + debug$4('retrieving options of last matching call'); + return (this.lastCall(nameOrMatcher, options) || [])[1]; + }); + FetchMock$2.lastResponse = formatDebug(function (nameOrMatcher, options) { + debug$4('retrieving respose of last matching call'); + console.warn("When doing all the following:\n- using node-fetch\n- responding with a real network response (using spy() or fallbackToNetwork)\n- using `fetchMock.LastResponse()`\n- awaiting the body content\n... the response will hang unless your source code also awaits the response body.\nThis is an unavoidable consequence of the nodejs implementation of streams.\n"); + var response = (this.lastCall(nameOrMatcher, options) || []).response; + + try { + var clonedResponse = response.clone(); + return clonedResponse; + } catch (err) { + Object.entries(response._fmResults).forEach(function (_ref6) { + var _ref7 = (0, _slicedToArray2$3["default"])(_ref6, 2), + name = _ref7[0], + result = _ref7[1]; + + response[name] = function () { + return result; + }; + }); + return response; + } + }); + FetchMock$2.called = formatDebug(function (nameOrMatcher, options) { + debug$4('checking if matching call was made'); + return Boolean(this.filterCalls(nameOrMatcher, options).length); + }); + FetchMock$2.flush = formatDebug( /*#__PURE__*/function () { + var _ref8 = (0, _asyncToGenerator2$2["default"])( /*#__PURE__*/_regenerator$2["default"].mark(function _callee(waitForResponseMethods) { + var queuedPromises; + return _regenerator$2["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + setDebugNamespace$1('flush'); + debug$4("flushing all fetch calls. ".concat(waitForResponseMethods ? '' : 'Not ', "waiting for response bodies to complete download")); + queuedPromises = this._holdingPromises; + this._holdingPromises = []; + debug$4("".concat(queuedPromises.length, " fetch calls to be awaited")); + _context.next = 7; + return Promise.all(queuedPromises); + + case 7: + debug$4("All fetch calls have completed"); + + if (!(waitForResponseMethods && this._holdingPromises.length)) { + _context.next = 13; + break; + } + + debug$4("Awaiting all fetch bodies to download"); + _context.next = 12; + return this.flush(waitForResponseMethods); + + case 12: + debug$4("All fetch bodies have completed downloading"); + + case 13: + setDebugNamespace$1(); + + case 14: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + return function (_x) { + return _ref8.apply(this, arguments); + }; + }()); + FetchMock$2.done = formatDebug(function (nameOrMatcher) { + var _this = this; + + setDebugPhase$2('inspect'); + setDebugNamespace$1('done'); + debug$4('Checking to see if expected calls have been made'); + var routesToCheck; + + if (nameOrMatcher && typeof nameOrMatcher !== 'boolean') { + debug$4('Checking to see if expected calls have been made for single route:', nameOrMatcher); + routesToCheck = [{ + identifier: nameOrMatcher + }]; + } else { + debug$4('Checking to see if expected calls have been made for all routes'); + routesToCheck = this.routes; + } // Can't use array.every because would exit after first failure, which would + // break the logging + + + var result = routesToCheck.map(function (_ref9) { + var identifier = _ref9.identifier; + + if (!_this.called(identifier)) { + debug$4('No calls made for route:', identifier); + console.warn("Warning: ".concat(identifier, " not called")); // eslint-disable-line + + return false; + } + + var expectedTimes = (_this.routes.find(function (r) { + return r.identifier === identifier; + }) || {}).repeat; + + if (!expectedTimes) { + debug$4('Route has been called at least once, and no expectation of more set:', identifier); + return true; + } + + var actualTimes = _this.filterCalls(identifier).length; + + debug$4("Route called ".concat(actualTimes, " times:"), identifier); + + if (expectedTimes > actualTimes) { + debug$4("Route called ".concat(actualTimes, " times, but expected ").concat(expectedTimes, ":"), identifier); + console.warn("Warning: ".concat(identifier, " only called ").concat(actualTimes, " times, but ").concat(expectedTimes, " expected")); // eslint-disable-line + + return false; + } else { + return true; + } + }).every(function (isDone) { + return isDone; + }); + setDebugNamespace$1(); + setDebugPhase$2(); + return result; + }); + var inspecting = FetchMock$2; + + var debug$5 = debug_1.debug; + + + + + + + + + + var FetchMock$3 = Object.assign({}, fetchHandler, setUpAndTearDown, inspecting); + + FetchMock$3.addMatcher = function (matcher) { + Route_1.addMatcher(matcher); + }; + + FetchMock$3.config = { + fallbackToNetwork: false, + includeContentLength: true, + sendAsJson: true, + warnOnFallback: true, + overwriteRoutes: undefined + }; + + FetchMock$3.createInstance = function () { + var _this = this; + + debug$5('Creating fetch-mock instance'); + var instance = Object.create(FetchMock$3); + instance._uncompiledRoutes = (this._uncompiledRoutes || []).slice(); + instance.routes = instance._uncompiledRoutes.map(function (config) { + return _this.compileRoute(config); + }); + instance.fallbackResponse = this.fallbackResponse || undefined; + instance.config = Object.assign({}, this.config || FetchMock$3.config); + instance._calls = []; + instance._holdingPromises = []; + instance.bindMethods(); + return instance; + }; + + FetchMock$3.compileRoute = function (config) { + return new Route_1(config, this); + }; + + FetchMock$3.bindMethods = function () { + this.fetchHandler = FetchMock$3.fetchHandler.bind(this); + this.reset = this.restore = FetchMock$3.reset.bind(this); + this.resetHistory = FetchMock$3.resetHistory.bind(this); + this.resetBehavior = FetchMock$3.resetBehavior.bind(this); + }; + + FetchMock$3.sandbox = function () { + debug$5('Creating sandboxed fetch-mock instance'); // this construct allows us to create a fetch-mock instance which is also + // a callable function, while circumventing circularity when defining the + // object that this function should be bound to + + var fetchMockProxy = function fetchMockProxy(url, options) { + return sandbox.fetchHandler(url, options); + }; + + var sandbox = Object.assign(fetchMockProxy, // Ensures that the entire returned object is a callable function + FetchMock$3, // prototype methods + this.createInstance(), // instance data + { + Headers: this.config.Headers, + Request: this.config.Request, + Response: this.config.Response + }); + sandbox.bindMethods(); + sandbox.isSandbox = true; + sandbox["default"] = sandbox; + return sandbox; + }; + + FetchMock$3.getOption = function (name) { + var route = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + return name in route ? route[name] : this.config[name]; + }; + + var lib = FetchMock$3; + + var statusTextMap = { + 100: 'Continue', + 101: 'Switching Protocols', + 102: 'Processing', + 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: 'Unordered Collection', + 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' + }; + var statusText = statusTextMap; + + var theGlobal = typeof window !== 'undefined' ? window : self; + + var setUrlImplementation = requestUtils.setUrlImplementation; + + setUrlImplementation(theGlobal.URL); + lib.global = theGlobal; + lib.statusTextMap = statusText; + lib.config = Object.assign(lib.config, { + Promise: theGlobal.Promise, + Request: theGlobal.Request, + Response: theGlobal.Response, + Headers: theGlobal.Headers + }); + var client = lib.createInstance(); + + return client; + +}))); diff --git a/es5/client-legacy-bundle.js b/es5/client-legacy-bundle.js new file mode 100644 index 00000000..15f729d6 --- /dev/null +++ b/es5/client-legacy-bundle.js @@ -0,0 +1,79513 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.fetchMock = factory()); +}(this, (function () { 'use strict'; + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function commonjsRequire () { + throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs'); + } + + function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; + } + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + function getCjsExportFromNamespace (n) { + return n && n['default'] || n; + } + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + var shallowEqual_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = shallowEqual; + + function shallowEqual(actual, expected) { + const keys = Object.keys(expected); + + for (const key of keys) { + if (actual[key] !== expected[key]) { + return false; + } + } + + return true; + } + }); + + unwrapExports(shallowEqual_1); + + var generated = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.isArrayExpression = isArrayExpression; + exports.isAssignmentExpression = isAssignmentExpression; + exports.isBinaryExpression = isBinaryExpression; + exports.isInterpreterDirective = isInterpreterDirective; + exports.isDirective = isDirective; + exports.isDirectiveLiteral = isDirectiveLiteral; + exports.isBlockStatement = isBlockStatement; + exports.isBreakStatement = isBreakStatement; + exports.isCallExpression = isCallExpression; + exports.isCatchClause = isCatchClause; + exports.isConditionalExpression = isConditionalExpression; + exports.isContinueStatement = isContinueStatement; + exports.isDebuggerStatement = isDebuggerStatement; + exports.isDoWhileStatement = isDoWhileStatement; + exports.isEmptyStatement = isEmptyStatement; + exports.isExpressionStatement = isExpressionStatement; + exports.isFile = isFile; + exports.isForInStatement = isForInStatement; + exports.isForStatement = isForStatement; + exports.isFunctionDeclaration = isFunctionDeclaration; + exports.isFunctionExpression = isFunctionExpression; + exports.isIdentifier = isIdentifier; + exports.isIfStatement = isIfStatement; + exports.isLabeledStatement = isLabeledStatement; + exports.isStringLiteral = isStringLiteral; + exports.isNumericLiteral = isNumericLiteral; + exports.isNullLiteral = isNullLiteral; + exports.isBooleanLiteral = isBooleanLiteral; + exports.isRegExpLiteral = isRegExpLiteral; + exports.isLogicalExpression = isLogicalExpression; + exports.isMemberExpression = isMemberExpression; + exports.isNewExpression = isNewExpression; + exports.isProgram = isProgram; + exports.isObjectExpression = isObjectExpression; + exports.isObjectMethod = isObjectMethod; + exports.isObjectProperty = isObjectProperty; + exports.isRestElement = isRestElement; + exports.isReturnStatement = isReturnStatement; + exports.isSequenceExpression = isSequenceExpression; + exports.isParenthesizedExpression = isParenthesizedExpression; + exports.isSwitchCase = isSwitchCase; + exports.isSwitchStatement = isSwitchStatement; + exports.isThisExpression = isThisExpression; + exports.isThrowStatement = isThrowStatement; + exports.isTryStatement = isTryStatement; + exports.isUnaryExpression = isUnaryExpression; + exports.isUpdateExpression = isUpdateExpression; + exports.isVariableDeclaration = isVariableDeclaration; + exports.isVariableDeclarator = isVariableDeclarator; + exports.isWhileStatement = isWhileStatement; + exports.isWithStatement = isWithStatement; + exports.isAssignmentPattern = isAssignmentPattern; + exports.isArrayPattern = isArrayPattern; + exports.isArrowFunctionExpression = isArrowFunctionExpression; + exports.isClassBody = isClassBody; + exports.isClassExpression = isClassExpression; + exports.isClassDeclaration = isClassDeclaration; + exports.isExportAllDeclaration = isExportAllDeclaration; + exports.isExportDefaultDeclaration = isExportDefaultDeclaration; + exports.isExportNamedDeclaration = isExportNamedDeclaration; + exports.isExportSpecifier = isExportSpecifier; + exports.isForOfStatement = isForOfStatement; + exports.isImportDeclaration = isImportDeclaration; + exports.isImportDefaultSpecifier = isImportDefaultSpecifier; + exports.isImportNamespaceSpecifier = isImportNamespaceSpecifier; + exports.isImportSpecifier = isImportSpecifier; + exports.isMetaProperty = isMetaProperty; + exports.isClassMethod = isClassMethod; + exports.isObjectPattern = isObjectPattern; + exports.isSpreadElement = isSpreadElement; + exports.isSuper = isSuper; + exports.isTaggedTemplateExpression = isTaggedTemplateExpression; + exports.isTemplateElement = isTemplateElement; + exports.isTemplateLiteral = isTemplateLiteral; + exports.isYieldExpression = isYieldExpression; + exports.isAwaitExpression = isAwaitExpression; + exports.isImport = isImport; + exports.isBigIntLiteral = isBigIntLiteral; + exports.isExportNamespaceSpecifier = isExportNamespaceSpecifier; + exports.isOptionalMemberExpression = isOptionalMemberExpression; + exports.isOptionalCallExpression = isOptionalCallExpression; + exports.isAnyTypeAnnotation = isAnyTypeAnnotation; + exports.isArrayTypeAnnotation = isArrayTypeAnnotation; + exports.isBooleanTypeAnnotation = isBooleanTypeAnnotation; + exports.isBooleanLiteralTypeAnnotation = isBooleanLiteralTypeAnnotation; + exports.isNullLiteralTypeAnnotation = isNullLiteralTypeAnnotation; + exports.isClassImplements = isClassImplements; + exports.isDeclareClass = isDeclareClass; + exports.isDeclareFunction = isDeclareFunction; + exports.isDeclareInterface = isDeclareInterface; + exports.isDeclareModule = isDeclareModule; + exports.isDeclareModuleExports = isDeclareModuleExports; + exports.isDeclareTypeAlias = isDeclareTypeAlias; + exports.isDeclareOpaqueType = isDeclareOpaqueType; + exports.isDeclareVariable = isDeclareVariable; + exports.isDeclareExportDeclaration = isDeclareExportDeclaration; + exports.isDeclareExportAllDeclaration = isDeclareExportAllDeclaration; + exports.isDeclaredPredicate = isDeclaredPredicate; + exports.isExistsTypeAnnotation = isExistsTypeAnnotation; + exports.isFunctionTypeAnnotation = isFunctionTypeAnnotation; + exports.isFunctionTypeParam = isFunctionTypeParam; + exports.isGenericTypeAnnotation = isGenericTypeAnnotation; + exports.isInferredPredicate = isInferredPredicate; + exports.isInterfaceExtends = isInterfaceExtends; + exports.isInterfaceDeclaration = isInterfaceDeclaration; + exports.isInterfaceTypeAnnotation = isInterfaceTypeAnnotation; + exports.isIntersectionTypeAnnotation = isIntersectionTypeAnnotation; + exports.isMixedTypeAnnotation = isMixedTypeAnnotation; + exports.isEmptyTypeAnnotation = isEmptyTypeAnnotation; + exports.isNullableTypeAnnotation = isNullableTypeAnnotation; + exports.isNumberLiteralTypeAnnotation = isNumberLiteralTypeAnnotation; + exports.isNumberTypeAnnotation = isNumberTypeAnnotation; + exports.isObjectTypeAnnotation = isObjectTypeAnnotation; + exports.isObjectTypeInternalSlot = isObjectTypeInternalSlot; + exports.isObjectTypeCallProperty = isObjectTypeCallProperty; + exports.isObjectTypeIndexer = isObjectTypeIndexer; + exports.isObjectTypeProperty = isObjectTypeProperty; + exports.isObjectTypeSpreadProperty = isObjectTypeSpreadProperty; + exports.isOpaqueType = isOpaqueType; + exports.isQualifiedTypeIdentifier = isQualifiedTypeIdentifier; + exports.isStringLiteralTypeAnnotation = isStringLiteralTypeAnnotation; + exports.isStringTypeAnnotation = isStringTypeAnnotation; + exports.isSymbolTypeAnnotation = isSymbolTypeAnnotation; + exports.isThisTypeAnnotation = isThisTypeAnnotation; + exports.isTupleTypeAnnotation = isTupleTypeAnnotation; + exports.isTypeofTypeAnnotation = isTypeofTypeAnnotation; + exports.isTypeAlias = isTypeAlias; + exports.isTypeAnnotation = isTypeAnnotation; + exports.isTypeCastExpression = isTypeCastExpression; + exports.isTypeParameter = isTypeParameter; + exports.isTypeParameterDeclaration = isTypeParameterDeclaration; + exports.isTypeParameterInstantiation = isTypeParameterInstantiation; + exports.isUnionTypeAnnotation = isUnionTypeAnnotation; + exports.isVariance = isVariance; + exports.isVoidTypeAnnotation = isVoidTypeAnnotation; + exports.isEnumDeclaration = isEnumDeclaration; + exports.isEnumBooleanBody = isEnumBooleanBody; + exports.isEnumNumberBody = isEnumNumberBody; + exports.isEnumStringBody = isEnumStringBody; + exports.isEnumSymbolBody = isEnumSymbolBody; + exports.isEnumBooleanMember = isEnumBooleanMember; + exports.isEnumNumberMember = isEnumNumberMember; + exports.isEnumStringMember = isEnumStringMember; + exports.isEnumDefaultedMember = isEnumDefaultedMember; + exports.isJSXAttribute = isJSXAttribute; + exports.isJSXClosingElement = isJSXClosingElement; + exports.isJSXElement = isJSXElement; + exports.isJSXEmptyExpression = isJSXEmptyExpression; + exports.isJSXExpressionContainer = isJSXExpressionContainer; + exports.isJSXSpreadChild = isJSXSpreadChild; + exports.isJSXIdentifier = isJSXIdentifier; + exports.isJSXMemberExpression = isJSXMemberExpression; + exports.isJSXNamespacedName = isJSXNamespacedName; + exports.isJSXOpeningElement = isJSXOpeningElement; + exports.isJSXSpreadAttribute = isJSXSpreadAttribute; + exports.isJSXText = isJSXText; + exports.isJSXFragment = isJSXFragment; + exports.isJSXOpeningFragment = isJSXOpeningFragment; + exports.isJSXClosingFragment = isJSXClosingFragment; + exports.isNoop = isNoop; + exports.isPlaceholder = isPlaceholder; + exports.isV8IntrinsicIdentifier = isV8IntrinsicIdentifier; + exports.isArgumentPlaceholder = isArgumentPlaceholder; + exports.isBindExpression = isBindExpression; + exports.isClassProperty = isClassProperty; + exports.isPipelineTopicExpression = isPipelineTopicExpression; + exports.isPipelineBareFunction = isPipelineBareFunction; + exports.isPipelinePrimaryTopicReference = isPipelinePrimaryTopicReference; + exports.isClassPrivateProperty = isClassPrivateProperty; + exports.isClassPrivateMethod = isClassPrivateMethod; + exports.isImportAttribute = isImportAttribute; + exports.isDecorator = isDecorator; + exports.isDoExpression = isDoExpression; + exports.isExportDefaultSpecifier = isExportDefaultSpecifier; + exports.isPrivateName = isPrivateName; + exports.isRecordExpression = isRecordExpression; + exports.isTupleExpression = isTupleExpression; + exports.isDecimalLiteral = isDecimalLiteral; + exports.isStaticBlock = isStaticBlock; + exports.isTSParameterProperty = isTSParameterProperty; + exports.isTSDeclareFunction = isTSDeclareFunction; + exports.isTSDeclareMethod = isTSDeclareMethod; + exports.isTSQualifiedName = isTSQualifiedName; + exports.isTSCallSignatureDeclaration = isTSCallSignatureDeclaration; + exports.isTSConstructSignatureDeclaration = isTSConstructSignatureDeclaration; + exports.isTSPropertySignature = isTSPropertySignature; + exports.isTSMethodSignature = isTSMethodSignature; + exports.isTSIndexSignature = isTSIndexSignature; + exports.isTSAnyKeyword = isTSAnyKeyword; + exports.isTSBooleanKeyword = isTSBooleanKeyword; + exports.isTSBigIntKeyword = isTSBigIntKeyword; + exports.isTSIntrinsicKeyword = isTSIntrinsicKeyword; + exports.isTSNeverKeyword = isTSNeverKeyword; + exports.isTSNullKeyword = isTSNullKeyword; + exports.isTSNumberKeyword = isTSNumberKeyword; + exports.isTSObjectKeyword = isTSObjectKeyword; + exports.isTSStringKeyword = isTSStringKeyword; + exports.isTSSymbolKeyword = isTSSymbolKeyword; + exports.isTSUndefinedKeyword = isTSUndefinedKeyword; + exports.isTSUnknownKeyword = isTSUnknownKeyword; + exports.isTSVoidKeyword = isTSVoidKeyword; + exports.isTSThisType = isTSThisType; + exports.isTSFunctionType = isTSFunctionType; + exports.isTSConstructorType = isTSConstructorType; + exports.isTSTypeReference = isTSTypeReference; + exports.isTSTypePredicate = isTSTypePredicate; + exports.isTSTypeQuery = isTSTypeQuery; + exports.isTSTypeLiteral = isTSTypeLiteral; + exports.isTSArrayType = isTSArrayType; + exports.isTSTupleType = isTSTupleType; + exports.isTSOptionalType = isTSOptionalType; + exports.isTSRestType = isTSRestType; + exports.isTSNamedTupleMember = isTSNamedTupleMember; + exports.isTSUnionType = isTSUnionType; + exports.isTSIntersectionType = isTSIntersectionType; + exports.isTSConditionalType = isTSConditionalType; + exports.isTSInferType = isTSInferType; + exports.isTSParenthesizedType = isTSParenthesizedType; + exports.isTSTypeOperator = isTSTypeOperator; + exports.isTSIndexedAccessType = isTSIndexedAccessType; + exports.isTSMappedType = isTSMappedType; + exports.isTSLiteralType = isTSLiteralType; + exports.isTSExpressionWithTypeArguments = isTSExpressionWithTypeArguments; + exports.isTSInterfaceDeclaration = isTSInterfaceDeclaration; + exports.isTSInterfaceBody = isTSInterfaceBody; + exports.isTSTypeAliasDeclaration = isTSTypeAliasDeclaration; + exports.isTSAsExpression = isTSAsExpression; + exports.isTSTypeAssertion = isTSTypeAssertion; + exports.isTSEnumDeclaration = isTSEnumDeclaration; + exports.isTSEnumMember = isTSEnumMember; + exports.isTSModuleDeclaration = isTSModuleDeclaration; + exports.isTSModuleBlock = isTSModuleBlock; + exports.isTSImportType = isTSImportType; + exports.isTSImportEqualsDeclaration = isTSImportEqualsDeclaration; + exports.isTSExternalModuleReference = isTSExternalModuleReference; + exports.isTSNonNullExpression = isTSNonNullExpression; + exports.isTSExportAssignment = isTSExportAssignment; + exports.isTSNamespaceExportDeclaration = isTSNamespaceExportDeclaration; + exports.isTSTypeAnnotation = isTSTypeAnnotation; + exports.isTSTypeParameterInstantiation = isTSTypeParameterInstantiation; + exports.isTSTypeParameterDeclaration = isTSTypeParameterDeclaration; + exports.isTSTypeParameter = isTSTypeParameter; + exports.isExpression = isExpression; + exports.isBinary = isBinary; + exports.isScopable = isScopable; + exports.isBlockParent = isBlockParent; + exports.isBlock = isBlock; + exports.isStatement = isStatement; + exports.isTerminatorless = isTerminatorless; + exports.isCompletionStatement = isCompletionStatement; + exports.isConditional = isConditional; + exports.isLoop = isLoop; + exports.isWhile = isWhile; + exports.isExpressionWrapper = isExpressionWrapper; + exports.isFor = isFor; + exports.isForXStatement = isForXStatement; + exports.isFunction = isFunction; + exports.isFunctionParent = isFunctionParent; + exports.isPureish = isPureish; + exports.isDeclaration = isDeclaration; + exports.isPatternLike = isPatternLike; + exports.isLVal = isLVal; + exports.isTSEntityName = isTSEntityName; + exports.isLiteral = isLiteral; + exports.isImmutable = isImmutable; + exports.isUserWhitespacable = isUserWhitespacable; + exports.isMethod = isMethod; + exports.isObjectMember = isObjectMember; + exports.isProperty = isProperty; + exports.isUnaryLike = isUnaryLike; + exports.isPattern = isPattern; + exports.isClass = isClass; + exports.isModuleDeclaration = isModuleDeclaration; + exports.isExportDeclaration = isExportDeclaration; + exports.isModuleSpecifier = isModuleSpecifier; + exports.isFlow = isFlow; + exports.isFlowType = isFlowType; + exports.isFlowBaseAnnotation = isFlowBaseAnnotation; + exports.isFlowDeclaration = isFlowDeclaration; + exports.isFlowPredicate = isFlowPredicate; + exports.isEnumBody = isEnumBody; + exports.isEnumMember = isEnumMember; + exports.isJSX = isJSX; + exports.isPrivate = isPrivate; + exports.isTSTypeElement = isTSTypeElement; + exports.isTSType = isTSType; + exports.isTSBaseType = isTSBaseType; + exports.isNumberLiteral = isNumberLiteral; + exports.isRegexLiteral = isRegexLiteral; + exports.isRestProperty = isRestProperty; + exports.isSpreadProperty = isSpreadProperty; + + var _shallowEqual = _interopRequireDefault(shallowEqual_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function isArrayExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ArrayExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isAssignmentExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "AssignmentExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isBinaryExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "BinaryExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isInterpreterDirective(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "InterpreterDirective") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isDirective(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Directive") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isDirectiveLiteral(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "DirectiveLiteral") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isBlockStatement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "BlockStatement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isBreakStatement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "BreakStatement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isCallExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "CallExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isCatchClause(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "CatchClause") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isConditionalExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ConditionalExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isContinueStatement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ContinueStatement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isDebuggerStatement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "DebuggerStatement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isDoWhileStatement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "DoWhileStatement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isEmptyStatement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "EmptyStatement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isExpressionStatement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ExpressionStatement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isFile(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "File") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isForInStatement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ForInStatement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isForStatement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ForStatement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isFunctionDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "FunctionDeclaration") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isFunctionExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "FunctionExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isIdentifier(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Identifier") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isIfStatement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "IfStatement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isLabeledStatement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "LabeledStatement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isStringLiteral(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "StringLiteral") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isNumericLiteral(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "NumericLiteral") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isNullLiteral(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "NullLiteral") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isBooleanLiteral(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "BooleanLiteral") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isRegExpLiteral(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "RegExpLiteral") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isLogicalExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "LogicalExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isMemberExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "MemberExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isNewExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "NewExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isProgram(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Program") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isObjectExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ObjectExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isObjectMethod(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ObjectMethod") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isObjectProperty(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ObjectProperty") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isRestElement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "RestElement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isReturnStatement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ReturnStatement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isSequenceExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "SequenceExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isParenthesizedExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ParenthesizedExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isSwitchCase(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "SwitchCase") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isSwitchStatement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "SwitchStatement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isThisExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ThisExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isThrowStatement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ThrowStatement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTryStatement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TryStatement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isUnaryExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "UnaryExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isUpdateExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "UpdateExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isVariableDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "VariableDeclaration") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isVariableDeclarator(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "VariableDeclarator") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isWhileStatement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "WhileStatement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isWithStatement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "WithStatement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isAssignmentPattern(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "AssignmentPattern") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isArrayPattern(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ArrayPattern") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isArrowFunctionExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ArrowFunctionExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isClassBody(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ClassBody") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isClassExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ClassExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isClassDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ClassDeclaration") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isExportAllDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ExportAllDeclaration") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isExportDefaultDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ExportDefaultDeclaration") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isExportNamedDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ExportNamedDeclaration") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isExportSpecifier(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ExportSpecifier") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isForOfStatement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ForOfStatement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isImportDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ImportDeclaration") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isImportDefaultSpecifier(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ImportDefaultSpecifier") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isImportNamespaceSpecifier(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ImportNamespaceSpecifier") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isImportSpecifier(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ImportSpecifier") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isMetaProperty(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "MetaProperty") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isClassMethod(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ClassMethod") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isObjectPattern(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ObjectPattern") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isSpreadElement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "SpreadElement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isSuper(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Super") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTaggedTemplateExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TaggedTemplateExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTemplateElement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TemplateElement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTemplateLiteral(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TemplateLiteral") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isYieldExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "YieldExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isAwaitExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "AwaitExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isImport(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Import") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isBigIntLiteral(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "BigIntLiteral") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isExportNamespaceSpecifier(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ExportNamespaceSpecifier") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isOptionalMemberExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "OptionalMemberExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isOptionalCallExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "OptionalCallExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isAnyTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "AnyTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isArrayTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ArrayTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isBooleanTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "BooleanTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isBooleanLiteralTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "BooleanLiteralTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isNullLiteralTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "NullLiteralTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isClassImplements(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ClassImplements") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isDeclareClass(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "DeclareClass") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isDeclareFunction(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "DeclareFunction") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isDeclareInterface(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "DeclareInterface") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isDeclareModule(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "DeclareModule") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isDeclareModuleExports(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "DeclareModuleExports") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isDeclareTypeAlias(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "DeclareTypeAlias") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isDeclareOpaqueType(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "DeclareOpaqueType") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isDeclareVariable(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "DeclareVariable") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isDeclareExportDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "DeclareExportDeclaration") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isDeclareExportAllDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "DeclareExportAllDeclaration") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isDeclaredPredicate(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "DeclaredPredicate") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isExistsTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ExistsTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isFunctionTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "FunctionTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isFunctionTypeParam(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "FunctionTypeParam") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isGenericTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "GenericTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isInferredPredicate(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "InferredPredicate") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isInterfaceExtends(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "InterfaceExtends") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isInterfaceDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "InterfaceDeclaration") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isInterfaceTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "InterfaceTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isIntersectionTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "IntersectionTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isMixedTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "MixedTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isEmptyTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "EmptyTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isNullableTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "NullableTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isNumberLiteralTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "NumberLiteralTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isNumberTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "NumberTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isObjectTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ObjectTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isObjectTypeInternalSlot(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ObjectTypeInternalSlot") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isObjectTypeCallProperty(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ObjectTypeCallProperty") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isObjectTypeIndexer(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ObjectTypeIndexer") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isObjectTypeProperty(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ObjectTypeProperty") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isObjectTypeSpreadProperty(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ObjectTypeSpreadProperty") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isOpaqueType(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "OpaqueType") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isQualifiedTypeIdentifier(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "QualifiedTypeIdentifier") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isStringLiteralTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "StringLiteralTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isStringTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "StringTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isSymbolTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "SymbolTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isThisTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ThisTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTupleTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TupleTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTypeofTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TypeofTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTypeAlias(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TypeAlias") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTypeCastExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TypeCastExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTypeParameter(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TypeParameter") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTypeParameterDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TypeParameterDeclaration") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTypeParameterInstantiation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TypeParameterInstantiation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isUnionTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "UnionTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isVariance(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Variance") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isVoidTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "VoidTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isEnumDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "EnumDeclaration") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isEnumBooleanBody(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "EnumBooleanBody") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isEnumNumberBody(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "EnumNumberBody") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isEnumStringBody(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "EnumStringBody") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isEnumSymbolBody(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "EnumSymbolBody") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isEnumBooleanMember(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "EnumBooleanMember") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isEnumNumberMember(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "EnumNumberMember") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isEnumStringMember(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "EnumStringMember") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isEnumDefaultedMember(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "EnumDefaultedMember") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isJSXAttribute(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "JSXAttribute") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isJSXClosingElement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "JSXClosingElement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isJSXElement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "JSXElement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isJSXEmptyExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "JSXEmptyExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isJSXExpressionContainer(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "JSXExpressionContainer") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isJSXSpreadChild(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "JSXSpreadChild") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isJSXIdentifier(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "JSXIdentifier") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isJSXMemberExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "JSXMemberExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isJSXNamespacedName(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "JSXNamespacedName") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isJSXOpeningElement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "JSXOpeningElement") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isJSXSpreadAttribute(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "JSXSpreadAttribute") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isJSXText(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "JSXText") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isJSXFragment(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "JSXFragment") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isJSXOpeningFragment(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "JSXOpeningFragment") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isJSXClosingFragment(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "JSXClosingFragment") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isNoop(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Noop") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isPlaceholder(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Placeholder") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isV8IntrinsicIdentifier(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "V8IntrinsicIdentifier") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isArgumentPlaceholder(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ArgumentPlaceholder") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isBindExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "BindExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isClassProperty(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ClassProperty") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isPipelineTopicExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "PipelineTopicExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isPipelineBareFunction(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "PipelineBareFunction") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isPipelinePrimaryTopicReference(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "PipelinePrimaryTopicReference") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isClassPrivateProperty(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ClassPrivateProperty") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isClassPrivateMethod(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ClassPrivateMethod") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isImportAttribute(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ImportAttribute") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isDecorator(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Decorator") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isDoExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "DoExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isExportDefaultSpecifier(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ExportDefaultSpecifier") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isPrivateName(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "PrivateName") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isRecordExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "RecordExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTupleExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TupleExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isDecimalLiteral(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "DecimalLiteral") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isStaticBlock(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "StaticBlock") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSParameterProperty(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSParameterProperty") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSDeclareFunction(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSDeclareFunction") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSDeclareMethod(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSDeclareMethod") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSQualifiedName(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSQualifiedName") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSCallSignatureDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSCallSignatureDeclaration") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSConstructSignatureDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSConstructSignatureDeclaration") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSPropertySignature(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSPropertySignature") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSMethodSignature(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSMethodSignature") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSIndexSignature(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSIndexSignature") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSAnyKeyword(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSAnyKeyword") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSBooleanKeyword(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSBooleanKeyword") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSBigIntKeyword(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSBigIntKeyword") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSIntrinsicKeyword(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSIntrinsicKeyword") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSNeverKeyword(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSNeverKeyword") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSNullKeyword(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSNullKeyword") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSNumberKeyword(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSNumberKeyword") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSObjectKeyword(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSObjectKeyword") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSStringKeyword(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSStringKeyword") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSSymbolKeyword(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSSymbolKeyword") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSUndefinedKeyword(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSUndefinedKeyword") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSUnknownKeyword(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSUnknownKeyword") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSVoidKeyword(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSVoidKeyword") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSThisType(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSThisType") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSFunctionType(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSFunctionType") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSConstructorType(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSConstructorType") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSTypeReference(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSTypeReference") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSTypePredicate(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSTypePredicate") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSTypeQuery(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSTypeQuery") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSTypeLiteral(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSTypeLiteral") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSArrayType(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSArrayType") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSTupleType(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSTupleType") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSOptionalType(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSOptionalType") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSRestType(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSRestType") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSNamedTupleMember(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSNamedTupleMember") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSUnionType(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSUnionType") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSIntersectionType(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSIntersectionType") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSConditionalType(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSConditionalType") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSInferType(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSInferType") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSParenthesizedType(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSParenthesizedType") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSTypeOperator(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSTypeOperator") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSIndexedAccessType(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSIndexedAccessType") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSMappedType(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSMappedType") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSLiteralType(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSLiteralType") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSExpressionWithTypeArguments(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSExpressionWithTypeArguments") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSInterfaceDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSInterfaceDeclaration") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSInterfaceBody(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSInterfaceBody") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSTypeAliasDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSTypeAliasDeclaration") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSAsExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSAsExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSTypeAssertion(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSTypeAssertion") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSEnumDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSEnumDeclaration") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSEnumMember(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSEnumMember") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSModuleDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSModuleDeclaration") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSModuleBlock(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSModuleBlock") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSImportType(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSImportType") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSImportEqualsDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSImportEqualsDeclaration") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSExternalModuleReference(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSExternalModuleReference") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSNonNullExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSNonNullExpression") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSExportAssignment(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSExportAssignment") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSNamespaceExportDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSNamespaceExportDeclaration") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSTypeAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSTypeAnnotation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSTypeParameterInstantiation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSTypeParameterInstantiation") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSTypeParameterDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSTypeParameterDeclaration") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSTypeParameter(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSTypeParameter") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isExpression(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Expression" || "ArrayExpression" === nodeType || "AssignmentExpression" === nodeType || "BinaryExpression" === nodeType || "CallExpression" === nodeType || "ConditionalExpression" === nodeType || "FunctionExpression" === nodeType || "Identifier" === nodeType || "StringLiteral" === nodeType || "NumericLiteral" === nodeType || "NullLiteral" === nodeType || "BooleanLiteral" === nodeType || "RegExpLiteral" === nodeType || "LogicalExpression" === nodeType || "MemberExpression" === nodeType || "NewExpression" === nodeType || "ObjectExpression" === nodeType || "SequenceExpression" === nodeType || "ParenthesizedExpression" === nodeType || "ThisExpression" === nodeType || "UnaryExpression" === nodeType || "UpdateExpression" === nodeType || "ArrowFunctionExpression" === nodeType || "ClassExpression" === nodeType || "MetaProperty" === nodeType || "Super" === nodeType || "TaggedTemplateExpression" === nodeType || "TemplateLiteral" === nodeType || "YieldExpression" === nodeType || "AwaitExpression" === nodeType || "Import" === nodeType || "BigIntLiteral" === nodeType || "OptionalMemberExpression" === nodeType || "OptionalCallExpression" === nodeType || "TypeCastExpression" === nodeType || "JSXElement" === nodeType || "JSXFragment" === nodeType || "BindExpression" === nodeType || "PipelinePrimaryTopicReference" === nodeType || "DoExpression" === nodeType || "RecordExpression" === nodeType || "TupleExpression" === nodeType || "DecimalLiteral" === nodeType || "TSAsExpression" === nodeType || "TSTypeAssertion" === nodeType || "TSNonNullExpression" === nodeType || nodeType === "Placeholder" && ("Expression" === node.expectedNode || "Identifier" === node.expectedNode || "StringLiteral" === node.expectedNode)) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isBinary(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Binary" || "BinaryExpression" === nodeType || "LogicalExpression" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isScopable(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Scopable" || "BlockStatement" === nodeType || "CatchClause" === nodeType || "DoWhileStatement" === nodeType || "ForInStatement" === nodeType || "ForStatement" === nodeType || "FunctionDeclaration" === nodeType || "FunctionExpression" === nodeType || "Program" === nodeType || "ObjectMethod" === nodeType || "SwitchStatement" === nodeType || "WhileStatement" === nodeType || "ArrowFunctionExpression" === nodeType || "ClassExpression" === nodeType || "ClassDeclaration" === nodeType || "ForOfStatement" === nodeType || "ClassMethod" === nodeType || "ClassPrivateMethod" === nodeType || "StaticBlock" === nodeType || "TSModuleBlock" === nodeType || nodeType === "Placeholder" && "BlockStatement" === node.expectedNode) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isBlockParent(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "BlockParent" || "BlockStatement" === nodeType || "CatchClause" === nodeType || "DoWhileStatement" === nodeType || "ForInStatement" === nodeType || "ForStatement" === nodeType || "FunctionDeclaration" === nodeType || "FunctionExpression" === nodeType || "Program" === nodeType || "ObjectMethod" === nodeType || "SwitchStatement" === nodeType || "WhileStatement" === nodeType || "ArrowFunctionExpression" === nodeType || "ForOfStatement" === nodeType || "ClassMethod" === nodeType || "ClassPrivateMethod" === nodeType || "StaticBlock" === nodeType || "TSModuleBlock" === nodeType || nodeType === "Placeholder" && "BlockStatement" === node.expectedNode) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isBlock(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Block" || "BlockStatement" === nodeType || "Program" === nodeType || "TSModuleBlock" === nodeType || nodeType === "Placeholder" && "BlockStatement" === node.expectedNode) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isStatement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Statement" || "BlockStatement" === nodeType || "BreakStatement" === nodeType || "ContinueStatement" === nodeType || "DebuggerStatement" === nodeType || "DoWhileStatement" === nodeType || "EmptyStatement" === nodeType || "ExpressionStatement" === nodeType || "ForInStatement" === nodeType || "ForStatement" === nodeType || "FunctionDeclaration" === nodeType || "IfStatement" === nodeType || "LabeledStatement" === nodeType || "ReturnStatement" === nodeType || "SwitchStatement" === nodeType || "ThrowStatement" === nodeType || "TryStatement" === nodeType || "VariableDeclaration" === nodeType || "WhileStatement" === nodeType || "WithStatement" === nodeType || "ClassDeclaration" === nodeType || "ExportAllDeclaration" === nodeType || "ExportDefaultDeclaration" === nodeType || "ExportNamedDeclaration" === nodeType || "ForOfStatement" === nodeType || "ImportDeclaration" === nodeType || "DeclareClass" === nodeType || "DeclareFunction" === nodeType || "DeclareInterface" === nodeType || "DeclareModule" === nodeType || "DeclareModuleExports" === nodeType || "DeclareTypeAlias" === nodeType || "DeclareOpaqueType" === nodeType || "DeclareVariable" === nodeType || "DeclareExportDeclaration" === nodeType || "DeclareExportAllDeclaration" === nodeType || "InterfaceDeclaration" === nodeType || "OpaqueType" === nodeType || "TypeAlias" === nodeType || "EnumDeclaration" === nodeType || "TSDeclareFunction" === nodeType || "TSInterfaceDeclaration" === nodeType || "TSTypeAliasDeclaration" === nodeType || "TSEnumDeclaration" === nodeType || "TSModuleDeclaration" === nodeType || "TSImportEqualsDeclaration" === nodeType || "TSExportAssignment" === nodeType || "TSNamespaceExportDeclaration" === nodeType || nodeType === "Placeholder" && ("Statement" === node.expectedNode || "Declaration" === node.expectedNode || "BlockStatement" === node.expectedNode)) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTerminatorless(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Terminatorless" || "BreakStatement" === nodeType || "ContinueStatement" === nodeType || "ReturnStatement" === nodeType || "ThrowStatement" === nodeType || "YieldExpression" === nodeType || "AwaitExpression" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isCompletionStatement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "CompletionStatement" || "BreakStatement" === nodeType || "ContinueStatement" === nodeType || "ReturnStatement" === nodeType || "ThrowStatement" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isConditional(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Conditional" || "ConditionalExpression" === nodeType || "IfStatement" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isLoop(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Loop" || "DoWhileStatement" === nodeType || "ForInStatement" === nodeType || "ForStatement" === nodeType || "WhileStatement" === nodeType || "ForOfStatement" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isWhile(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "While" || "DoWhileStatement" === nodeType || "WhileStatement" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isExpressionWrapper(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ExpressionWrapper" || "ExpressionStatement" === nodeType || "ParenthesizedExpression" === nodeType || "TypeCastExpression" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isFor(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "For" || "ForInStatement" === nodeType || "ForStatement" === nodeType || "ForOfStatement" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isForXStatement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ForXStatement" || "ForInStatement" === nodeType || "ForOfStatement" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isFunction(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Function" || "FunctionDeclaration" === nodeType || "FunctionExpression" === nodeType || "ObjectMethod" === nodeType || "ArrowFunctionExpression" === nodeType || "ClassMethod" === nodeType || "ClassPrivateMethod" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isFunctionParent(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "FunctionParent" || "FunctionDeclaration" === nodeType || "FunctionExpression" === nodeType || "ObjectMethod" === nodeType || "ArrowFunctionExpression" === nodeType || "ClassMethod" === nodeType || "ClassPrivateMethod" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isPureish(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Pureish" || "FunctionDeclaration" === nodeType || "FunctionExpression" === nodeType || "StringLiteral" === nodeType || "NumericLiteral" === nodeType || "NullLiteral" === nodeType || "BooleanLiteral" === nodeType || "RegExpLiteral" === nodeType || "ArrowFunctionExpression" === nodeType || "BigIntLiteral" === nodeType || "DecimalLiteral" === nodeType || nodeType === "Placeholder" && "StringLiteral" === node.expectedNode) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Declaration" || "FunctionDeclaration" === nodeType || "VariableDeclaration" === nodeType || "ClassDeclaration" === nodeType || "ExportAllDeclaration" === nodeType || "ExportDefaultDeclaration" === nodeType || "ExportNamedDeclaration" === nodeType || "ImportDeclaration" === nodeType || "DeclareClass" === nodeType || "DeclareFunction" === nodeType || "DeclareInterface" === nodeType || "DeclareModule" === nodeType || "DeclareModuleExports" === nodeType || "DeclareTypeAlias" === nodeType || "DeclareOpaqueType" === nodeType || "DeclareVariable" === nodeType || "DeclareExportDeclaration" === nodeType || "DeclareExportAllDeclaration" === nodeType || "InterfaceDeclaration" === nodeType || "OpaqueType" === nodeType || "TypeAlias" === nodeType || "EnumDeclaration" === nodeType || "TSDeclareFunction" === nodeType || "TSInterfaceDeclaration" === nodeType || "TSTypeAliasDeclaration" === nodeType || "TSEnumDeclaration" === nodeType || "TSModuleDeclaration" === nodeType || nodeType === "Placeholder" && "Declaration" === node.expectedNode) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isPatternLike(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "PatternLike" || "Identifier" === nodeType || "RestElement" === nodeType || "AssignmentPattern" === nodeType || "ArrayPattern" === nodeType || "ObjectPattern" === nodeType || nodeType === "Placeholder" && ("Pattern" === node.expectedNode || "Identifier" === node.expectedNode)) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isLVal(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "LVal" || "Identifier" === nodeType || "MemberExpression" === nodeType || "RestElement" === nodeType || "AssignmentPattern" === nodeType || "ArrayPattern" === nodeType || "ObjectPattern" === nodeType || "TSParameterProperty" === nodeType || nodeType === "Placeholder" && ("Pattern" === node.expectedNode || "Identifier" === node.expectedNode)) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSEntityName(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSEntityName" || "Identifier" === nodeType || "TSQualifiedName" === nodeType || nodeType === "Placeholder" && "Identifier" === node.expectedNode) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isLiteral(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Literal" || "StringLiteral" === nodeType || "NumericLiteral" === nodeType || "NullLiteral" === nodeType || "BooleanLiteral" === nodeType || "RegExpLiteral" === nodeType || "TemplateLiteral" === nodeType || "BigIntLiteral" === nodeType || "DecimalLiteral" === nodeType || nodeType === "Placeholder" && "StringLiteral" === node.expectedNode) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isImmutable(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Immutable" || "StringLiteral" === nodeType || "NumericLiteral" === nodeType || "NullLiteral" === nodeType || "BooleanLiteral" === nodeType || "BigIntLiteral" === nodeType || "JSXAttribute" === nodeType || "JSXClosingElement" === nodeType || "JSXElement" === nodeType || "JSXExpressionContainer" === nodeType || "JSXSpreadChild" === nodeType || "JSXOpeningElement" === nodeType || "JSXText" === nodeType || "JSXFragment" === nodeType || "JSXOpeningFragment" === nodeType || "JSXClosingFragment" === nodeType || "DecimalLiteral" === nodeType || nodeType === "Placeholder" && "StringLiteral" === node.expectedNode) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isUserWhitespacable(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "UserWhitespacable" || "ObjectMethod" === nodeType || "ObjectProperty" === nodeType || "ObjectTypeInternalSlot" === nodeType || "ObjectTypeCallProperty" === nodeType || "ObjectTypeIndexer" === nodeType || "ObjectTypeProperty" === nodeType || "ObjectTypeSpreadProperty" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isMethod(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Method" || "ObjectMethod" === nodeType || "ClassMethod" === nodeType || "ClassPrivateMethod" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isObjectMember(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ObjectMember" || "ObjectMethod" === nodeType || "ObjectProperty" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isProperty(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Property" || "ObjectProperty" === nodeType || "ClassProperty" === nodeType || "ClassPrivateProperty" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isUnaryLike(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "UnaryLike" || "UnaryExpression" === nodeType || "SpreadElement" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isPattern(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Pattern" || "AssignmentPattern" === nodeType || "ArrayPattern" === nodeType || "ObjectPattern" === nodeType || nodeType === "Placeholder" && "Pattern" === node.expectedNode) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isClass(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Class" || "ClassExpression" === nodeType || "ClassDeclaration" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isModuleDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ModuleDeclaration" || "ExportAllDeclaration" === nodeType || "ExportDefaultDeclaration" === nodeType || "ExportNamedDeclaration" === nodeType || "ImportDeclaration" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isExportDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ExportDeclaration" || "ExportAllDeclaration" === nodeType || "ExportDefaultDeclaration" === nodeType || "ExportNamedDeclaration" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isModuleSpecifier(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "ModuleSpecifier" || "ExportSpecifier" === nodeType || "ImportDefaultSpecifier" === nodeType || "ImportNamespaceSpecifier" === nodeType || "ImportSpecifier" === nodeType || "ExportNamespaceSpecifier" === nodeType || "ExportDefaultSpecifier" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isFlow(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Flow" || "AnyTypeAnnotation" === nodeType || "ArrayTypeAnnotation" === nodeType || "BooleanTypeAnnotation" === nodeType || "BooleanLiteralTypeAnnotation" === nodeType || "NullLiteralTypeAnnotation" === nodeType || "ClassImplements" === nodeType || "DeclareClass" === nodeType || "DeclareFunction" === nodeType || "DeclareInterface" === nodeType || "DeclareModule" === nodeType || "DeclareModuleExports" === nodeType || "DeclareTypeAlias" === nodeType || "DeclareOpaqueType" === nodeType || "DeclareVariable" === nodeType || "DeclareExportDeclaration" === nodeType || "DeclareExportAllDeclaration" === nodeType || "DeclaredPredicate" === nodeType || "ExistsTypeAnnotation" === nodeType || "FunctionTypeAnnotation" === nodeType || "FunctionTypeParam" === nodeType || "GenericTypeAnnotation" === nodeType || "InferredPredicate" === nodeType || "InterfaceExtends" === nodeType || "InterfaceDeclaration" === nodeType || "InterfaceTypeAnnotation" === nodeType || "IntersectionTypeAnnotation" === nodeType || "MixedTypeAnnotation" === nodeType || "EmptyTypeAnnotation" === nodeType || "NullableTypeAnnotation" === nodeType || "NumberLiteralTypeAnnotation" === nodeType || "NumberTypeAnnotation" === nodeType || "ObjectTypeAnnotation" === nodeType || "ObjectTypeInternalSlot" === nodeType || "ObjectTypeCallProperty" === nodeType || "ObjectTypeIndexer" === nodeType || "ObjectTypeProperty" === nodeType || "ObjectTypeSpreadProperty" === nodeType || "OpaqueType" === nodeType || "QualifiedTypeIdentifier" === nodeType || "StringLiteralTypeAnnotation" === nodeType || "StringTypeAnnotation" === nodeType || "SymbolTypeAnnotation" === nodeType || "ThisTypeAnnotation" === nodeType || "TupleTypeAnnotation" === nodeType || "TypeofTypeAnnotation" === nodeType || "TypeAlias" === nodeType || "TypeAnnotation" === nodeType || "TypeCastExpression" === nodeType || "TypeParameter" === nodeType || "TypeParameterDeclaration" === nodeType || "TypeParameterInstantiation" === nodeType || "UnionTypeAnnotation" === nodeType || "Variance" === nodeType || "VoidTypeAnnotation" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isFlowType(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "FlowType" || "AnyTypeAnnotation" === nodeType || "ArrayTypeAnnotation" === nodeType || "BooleanTypeAnnotation" === nodeType || "BooleanLiteralTypeAnnotation" === nodeType || "NullLiteralTypeAnnotation" === nodeType || "ExistsTypeAnnotation" === nodeType || "FunctionTypeAnnotation" === nodeType || "GenericTypeAnnotation" === nodeType || "InterfaceTypeAnnotation" === nodeType || "IntersectionTypeAnnotation" === nodeType || "MixedTypeAnnotation" === nodeType || "EmptyTypeAnnotation" === nodeType || "NullableTypeAnnotation" === nodeType || "NumberLiteralTypeAnnotation" === nodeType || "NumberTypeAnnotation" === nodeType || "ObjectTypeAnnotation" === nodeType || "StringLiteralTypeAnnotation" === nodeType || "StringTypeAnnotation" === nodeType || "SymbolTypeAnnotation" === nodeType || "ThisTypeAnnotation" === nodeType || "TupleTypeAnnotation" === nodeType || "TypeofTypeAnnotation" === nodeType || "UnionTypeAnnotation" === nodeType || "VoidTypeAnnotation" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isFlowBaseAnnotation(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "FlowBaseAnnotation" || "AnyTypeAnnotation" === nodeType || "BooleanTypeAnnotation" === nodeType || "NullLiteralTypeAnnotation" === nodeType || "MixedTypeAnnotation" === nodeType || "EmptyTypeAnnotation" === nodeType || "NumberTypeAnnotation" === nodeType || "StringTypeAnnotation" === nodeType || "SymbolTypeAnnotation" === nodeType || "ThisTypeAnnotation" === nodeType || "VoidTypeAnnotation" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isFlowDeclaration(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "FlowDeclaration" || "DeclareClass" === nodeType || "DeclareFunction" === nodeType || "DeclareInterface" === nodeType || "DeclareModule" === nodeType || "DeclareModuleExports" === nodeType || "DeclareTypeAlias" === nodeType || "DeclareOpaqueType" === nodeType || "DeclareVariable" === nodeType || "DeclareExportDeclaration" === nodeType || "DeclareExportAllDeclaration" === nodeType || "InterfaceDeclaration" === nodeType || "OpaqueType" === nodeType || "TypeAlias" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isFlowPredicate(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "FlowPredicate" || "DeclaredPredicate" === nodeType || "InferredPredicate" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isEnumBody(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "EnumBody" || "EnumBooleanBody" === nodeType || "EnumNumberBody" === nodeType || "EnumStringBody" === nodeType || "EnumSymbolBody" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isEnumMember(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "EnumMember" || "EnumBooleanMember" === nodeType || "EnumNumberMember" === nodeType || "EnumStringMember" === nodeType || "EnumDefaultedMember" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isJSX(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "JSX" || "JSXAttribute" === nodeType || "JSXClosingElement" === nodeType || "JSXElement" === nodeType || "JSXEmptyExpression" === nodeType || "JSXExpressionContainer" === nodeType || "JSXSpreadChild" === nodeType || "JSXIdentifier" === nodeType || "JSXMemberExpression" === nodeType || "JSXNamespacedName" === nodeType || "JSXOpeningElement" === nodeType || "JSXSpreadAttribute" === nodeType || "JSXText" === nodeType || "JSXFragment" === nodeType || "JSXOpeningFragment" === nodeType || "JSXClosingFragment" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isPrivate(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "Private" || "ClassPrivateProperty" === nodeType || "ClassPrivateMethod" === nodeType || "PrivateName" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSTypeElement(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSTypeElement" || "TSCallSignatureDeclaration" === nodeType || "TSConstructSignatureDeclaration" === nodeType || "TSPropertySignature" === nodeType || "TSMethodSignature" === nodeType || "TSIndexSignature" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSType(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSType" || "TSAnyKeyword" === nodeType || "TSBooleanKeyword" === nodeType || "TSBigIntKeyword" === nodeType || "TSIntrinsicKeyword" === nodeType || "TSNeverKeyword" === nodeType || "TSNullKeyword" === nodeType || "TSNumberKeyword" === nodeType || "TSObjectKeyword" === nodeType || "TSStringKeyword" === nodeType || "TSSymbolKeyword" === nodeType || "TSUndefinedKeyword" === nodeType || "TSUnknownKeyword" === nodeType || "TSVoidKeyword" === nodeType || "TSThisType" === nodeType || "TSFunctionType" === nodeType || "TSConstructorType" === nodeType || "TSTypeReference" === nodeType || "TSTypePredicate" === nodeType || "TSTypeQuery" === nodeType || "TSTypeLiteral" === nodeType || "TSArrayType" === nodeType || "TSTupleType" === nodeType || "TSOptionalType" === nodeType || "TSRestType" === nodeType || "TSUnionType" === nodeType || "TSIntersectionType" === nodeType || "TSConditionalType" === nodeType || "TSInferType" === nodeType || "TSParenthesizedType" === nodeType || "TSTypeOperator" === nodeType || "TSIndexedAccessType" === nodeType || "TSMappedType" === nodeType || "TSLiteralType" === nodeType || "TSExpressionWithTypeArguments" === nodeType || "TSImportType" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isTSBaseType(node, opts) { + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "TSBaseType" || "TSAnyKeyword" === nodeType || "TSBooleanKeyword" === nodeType || "TSBigIntKeyword" === nodeType || "TSIntrinsicKeyword" === nodeType || "TSNeverKeyword" === nodeType || "TSNullKeyword" === nodeType || "TSNumberKeyword" === nodeType || "TSObjectKeyword" === nodeType || "TSStringKeyword" === nodeType || "TSSymbolKeyword" === nodeType || "TSUndefinedKeyword" === nodeType || "TSUnknownKeyword" === nodeType || "TSVoidKeyword" === nodeType || "TSThisType" === nodeType || "TSLiteralType" === nodeType) { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isNumberLiteral(node, opts) { + console.trace("The node type NumberLiteral has been renamed to NumericLiteral"); + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "NumberLiteral") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isRegexLiteral(node, opts) { + console.trace("The node type RegexLiteral has been renamed to RegExpLiteral"); + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "RegexLiteral") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isRestProperty(node, opts) { + console.trace("The node type RestProperty has been renamed to RestElement"); + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "RestProperty") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + + function isSpreadProperty(node, opts) { + console.trace("The node type SpreadProperty has been renamed to SpreadElement"); + if (!node) return false; + const nodeType = node.type; + + if (nodeType === "SpreadProperty") { + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + + return false; + } + }); + + unwrapExports(generated); + var generated_1 = generated.isArrayExpression; + var generated_2 = generated.isAssignmentExpression; + var generated_3 = generated.isBinaryExpression; + var generated_4 = generated.isInterpreterDirective; + var generated_5 = generated.isDirective; + var generated_6 = generated.isDirectiveLiteral; + var generated_7 = generated.isBlockStatement; + var generated_8 = generated.isBreakStatement; + var generated_9 = generated.isCallExpression; + var generated_10 = generated.isCatchClause; + var generated_11 = generated.isConditionalExpression; + var generated_12 = generated.isContinueStatement; + var generated_13 = generated.isDebuggerStatement; + var generated_14 = generated.isDoWhileStatement; + var generated_15 = generated.isEmptyStatement; + var generated_16 = generated.isExpressionStatement; + var generated_17 = generated.isFile; + var generated_18 = generated.isForInStatement; + var generated_19 = generated.isForStatement; + var generated_20 = generated.isFunctionDeclaration; + var generated_21 = generated.isFunctionExpression; + var generated_22 = generated.isIdentifier; + var generated_23 = generated.isIfStatement; + var generated_24 = generated.isLabeledStatement; + var generated_25 = generated.isStringLiteral; + var generated_26 = generated.isNumericLiteral; + var generated_27 = generated.isNullLiteral; + var generated_28 = generated.isBooleanLiteral; + var generated_29 = generated.isRegExpLiteral; + var generated_30 = generated.isLogicalExpression; + var generated_31 = generated.isMemberExpression; + var generated_32 = generated.isNewExpression; + var generated_33 = generated.isProgram; + var generated_34 = generated.isObjectExpression; + var generated_35 = generated.isObjectMethod; + var generated_36 = generated.isObjectProperty; + var generated_37 = generated.isRestElement; + var generated_38 = generated.isReturnStatement; + var generated_39 = generated.isSequenceExpression; + var generated_40 = generated.isParenthesizedExpression; + var generated_41 = generated.isSwitchCase; + var generated_42 = generated.isSwitchStatement; + var generated_43 = generated.isThisExpression; + var generated_44 = generated.isThrowStatement; + var generated_45 = generated.isTryStatement; + var generated_46 = generated.isUnaryExpression; + var generated_47 = generated.isUpdateExpression; + var generated_48 = generated.isVariableDeclaration; + var generated_49 = generated.isVariableDeclarator; + var generated_50 = generated.isWhileStatement; + var generated_51 = generated.isWithStatement; + var generated_52 = generated.isAssignmentPattern; + var generated_53 = generated.isArrayPattern; + var generated_54 = generated.isArrowFunctionExpression; + var generated_55 = generated.isClassBody; + var generated_56 = generated.isClassExpression; + var generated_57 = generated.isClassDeclaration; + var generated_58 = generated.isExportAllDeclaration; + var generated_59 = generated.isExportDefaultDeclaration; + var generated_60 = generated.isExportNamedDeclaration; + var generated_61 = generated.isExportSpecifier; + var generated_62 = generated.isForOfStatement; + var generated_63 = generated.isImportDeclaration; + var generated_64 = generated.isImportDefaultSpecifier; + var generated_65 = generated.isImportNamespaceSpecifier; + var generated_66 = generated.isImportSpecifier; + var generated_67 = generated.isMetaProperty; + var generated_68 = generated.isClassMethod; + var generated_69 = generated.isObjectPattern; + var generated_70 = generated.isSpreadElement; + var generated_71 = generated.isSuper; + var generated_72 = generated.isTaggedTemplateExpression; + var generated_73 = generated.isTemplateElement; + var generated_74 = generated.isTemplateLiteral; + var generated_75 = generated.isYieldExpression; + var generated_76 = generated.isAwaitExpression; + var generated_77 = generated.isImport; + var generated_78 = generated.isBigIntLiteral; + var generated_79 = generated.isExportNamespaceSpecifier; + var generated_80 = generated.isOptionalMemberExpression; + var generated_81 = generated.isOptionalCallExpression; + var generated_82 = generated.isAnyTypeAnnotation; + var generated_83 = generated.isArrayTypeAnnotation; + var generated_84 = generated.isBooleanTypeAnnotation; + var generated_85 = generated.isBooleanLiteralTypeAnnotation; + var generated_86 = generated.isNullLiteralTypeAnnotation; + var generated_87 = generated.isClassImplements; + var generated_88 = generated.isDeclareClass; + var generated_89 = generated.isDeclareFunction; + var generated_90 = generated.isDeclareInterface; + var generated_91 = generated.isDeclareModule; + var generated_92 = generated.isDeclareModuleExports; + var generated_93 = generated.isDeclareTypeAlias; + var generated_94 = generated.isDeclareOpaqueType; + var generated_95 = generated.isDeclareVariable; + var generated_96 = generated.isDeclareExportDeclaration; + var generated_97 = generated.isDeclareExportAllDeclaration; + var generated_98 = generated.isDeclaredPredicate; + var generated_99 = generated.isExistsTypeAnnotation; + var generated_100 = generated.isFunctionTypeAnnotation; + var generated_101 = generated.isFunctionTypeParam; + var generated_102 = generated.isGenericTypeAnnotation; + var generated_103 = generated.isInferredPredicate; + var generated_104 = generated.isInterfaceExtends; + var generated_105 = generated.isInterfaceDeclaration; + var generated_106 = generated.isInterfaceTypeAnnotation; + var generated_107 = generated.isIntersectionTypeAnnotation; + var generated_108 = generated.isMixedTypeAnnotation; + var generated_109 = generated.isEmptyTypeAnnotation; + var generated_110 = generated.isNullableTypeAnnotation; + var generated_111 = generated.isNumberLiteralTypeAnnotation; + var generated_112 = generated.isNumberTypeAnnotation; + var generated_113 = generated.isObjectTypeAnnotation; + var generated_114 = generated.isObjectTypeInternalSlot; + var generated_115 = generated.isObjectTypeCallProperty; + var generated_116 = generated.isObjectTypeIndexer; + var generated_117 = generated.isObjectTypeProperty; + var generated_118 = generated.isObjectTypeSpreadProperty; + var generated_119 = generated.isOpaqueType; + var generated_120 = generated.isQualifiedTypeIdentifier; + var generated_121 = generated.isStringLiteralTypeAnnotation; + var generated_122 = generated.isStringTypeAnnotation; + var generated_123 = generated.isSymbolTypeAnnotation; + var generated_124 = generated.isThisTypeAnnotation; + var generated_125 = generated.isTupleTypeAnnotation; + var generated_126 = generated.isTypeofTypeAnnotation; + var generated_127 = generated.isTypeAlias; + var generated_128 = generated.isTypeAnnotation; + var generated_129 = generated.isTypeCastExpression; + var generated_130 = generated.isTypeParameter; + var generated_131 = generated.isTypeParameterDeclaration; + var generated_132 = generated.isTypeParameterInstantiation; + var generated_133 = generated.isUnionTypeAnnotation; + var generated_134 = generated.isVariance; + var generated_135 = generated.isVoidTypeAnnotation; + var generated_136 = generated.isEnumDeclaration; + var generated_137 = generated.isEnumBooleanBody; + var generated_138 = generated.isEnumNumberBody; + var generated_139 = generated.isEnumStringBody; + var generated_140 = generated.isEnumSymbolBody; + var generated_141 = generated.isEnumBooleanMember; + var generated_142 = generated.isEnumNumberMember; + var generated_143 = generated.isEnumStringMember; + var generated_144 = generated.isEnumDefaultedMember; + var generated_145 = generated.isJSXAttribute; + var generated_146 = generated.isJSXClosingElement; + var generated_147 = generated.isJSXElement; + var generated_148 = generated.isJSXEmptyExpression; + var generated_149 = generated.isJSXExpressionContainer; + var generated_150 = generated.isJSXSpreadChild; + var generated_151 = generated.isJSXIdentifier; + var generated_152 = generated.isJSXMemberExpression; + var generated_153 = generated.isJSXNamespacedName; + var generated_154 = generated.isJSXOpeningElement; + var generated_155 = generated.isJSXSpreadAttribute; + var generated_156 = generated.isJSXText; + var generated_157 = generated.isJSXFragment; + var generated_158 = generated.isJSXOpeningFragment; + var generated_159 = generated.isJSXClosingFragment; + var generated_160 = generated.isNoop; + var generated_161 = generated.isPlaceholder; + var generated_162 = generated.isV8IntrinsicIdentifier; + var generated_163 = generated.isArgumentPlaceholder; + var generated_164 = generated.isBindExpression; + var generated_165 = generated.isClassProperty; + var generated_166 = generated.isPipelineTopicExpression; + var generated_167 = generated.isPipelineBareFunction; + var generated_168 = generated.isPipelinePrimaryTopicReference; + var generated_169 = generated.isClassPrivateProperty; + var generated_170 = generated.isClassPrivateMethod; + var generated_171 = generated.isImportAttribute; + var generated_172 = generated.isDecorator; + var generated_173 = generated.isDoExpression; + var generated_174 = generated.isExportDefaultSpecifier; + var generated_175 = generated.isPrivateName; + var generated_176 = generated.isRecordExpression; + var generated_177 = generated.isTupleExpression; + var generated_178 = generated.isDecimalLiteral; + var generated_179 = generated.isStaticBlock; + var generated_180 = generated.isTSParameterProperty; + var generated_181 = generated.isTSDeclareFunction; + var generated_182 = generated.isTSDeclareMethod; + var generated_183 = generated.isTSQualifiedName; + var generated_184 = generated.isTSCallSignatureDeclaration; + var generated_185 = generated.isTSConstructSignatureDeclaration; + var generated_186 = generated.isTSPropertySignature; + var generated_187 = generated.isTSMethodSignature; + var generated_188 = generated.isTSIndexSignature; + var generated_189 = generated.isTSAnyKeyword; + var generated_190 = generated.isTSBooleanKeyword; + var generated_191 = generated.isTSBigIntKeyword; + var generated_192 = generated.isTSIntrinsicKeyword; + var generated_193 = generated.isTSNeverKeyword; + var generated_194 = generated.isTSNullKeyword; + var generated_195 = generated.isTSNumberKeyword; + var generated_196 = generated.isTSObjectKeyword; + var generated_197 = generated.isTSStringKeyword; + var generated_198 = generated.isTSSymbolKeyword; + var generated_199 = generated.isTSUndefinedKeyword; + var generated_200 = generated.isTSUnknownKeyword; + var generated_201 = generated.isTSVoidKeyword; + var generated_202 = generated.isTSThisType; + var generated_203 = generated.isTSFunctionType; + var generated_204 = generated.isTSConstructorType; + var generated_205 = generated.isTSTypeReference; + var generated_206 = generated.isTSTypePredicate; + var generated_207 = generated.isTSTypeQuery; + var generated_208 = generated.isTSTypeLiteral; + var generated_209 = generated.isTSArrayType; + var generated_210 = generated.isTSTupleType; + var generated_211 = generated.isTSOptionalType; + var generated_212 = generated.isTSRestType; + var generated_213 = generated.isTSNamedTupleMember; + var generated_214 = generated.isTSUnionType; + var generated_215 = generated.isTSIntersectionType; + var generated_216 = generated.isTSConditionalType; + var generated_217 = generated.isTSInferType; + var generated_218 = generated.isTSParenthesizedType; + var generated_219 = generated.isTSTypeOperator; + var generated_220 = generated.isTSIndexedAccessType; + var generated_221 = generated.isTSMappedType; + var generated_222 = generated.isTSLiteralType; + var generated_223 = generated.isTSExpressionWithTypeArguments; + var generated_224 = generated.isTSInterfaceDeclaration; + var generated_225 = generated.isTSInterfaceBody; + var generated_226 = generated.isTSTypeAliasDeclaration; + var generated_227 = generated.isTSAsExpression; + var generated_228 = generated.isTSTypeAssertion; + var generated_229 = generated.isTSEnumDeclaration; + var generated_230 = generated.isTSEnumMember; + var generated_231 = generated.isTSModuleDeclaration; + var generated_232 = generated.isTSModuleBlock; + var generated_233 = generated.isTSImportType; + var generated_234 = generated.isTSImportEqualsDeclaration; + var generated_235 = generated.isTSExternalModuleReference; + var generated_236 = generated.isTSNonNullExpression; + var generated_237 = generated.isTSExportAssignment; + var generated_238 = generated.isTSNamespaceExportDeclaration; + var generated_239 = generated.isTSTypeAnnotation; + var generated_240 = generated.isTSTypeParameterInstantiation; + var generated_241 = generated.isTSTypeParameterDeclaration; + var generated_242 = generated.isTSTypeParameter; + var generated_243 = generated.isExpression; + var generated_244 = generated.isBinary; + var generated_245 = generated.isScopable; + var generated_246 = generated.isBlockParent; + var generated_247 = generated.isBlock; + var generated_248 = generated.isStatement; + var generated_249 = generated.isTerminatorless; + var generated_250 = generated.isCompletionStatement; + var generated_251 = generated.isConditional; + var generated_252 = generated.isLoop; + var generated_253 = generated.isWhile; + var generated_254 = generated.isExpressionWrapper; + var generated_255 = generated.isFor; + var generated_256 = generated.isForXStatement; + var generated_257 = generated.isFunction; + var generated_258 = generated.isFunctionParent; + var generated_259 = generated.isPureish; + var generated_260 = generated.isDeclaration; + var generated_261 = generated.isPatternLike; + var generated_262 = generated.isLVal; + var generated_263 = generated.isTSEntityName; + var generated_264 = generated.isLiteral; + var generated_265 = generated.isImmutable; + var generated_266 = generated.isUserWhitespacable; + var generated_267 = generated.isMethod; + var generated_268 = generated.isObjectMember; + var generated_269 = generated.isProperty; + var generated_270 = generated.isUnaryLike; + var generated_271 = generated.isPattern; + var generated_272 = generated.isClass; + var generated_273 = generated.isModuleDeclaration; + var generated_274 = generated.isExportDeclaration; + var generated_275 = generated.isModuleSpecifier; + var generated_276 = generated.isFlow; + var generated_277 = generated.isFlowType; + var generated_278 = generated.isFlowBaseAnnotation; + var generated_279 = generated.isFlowDeclaration; + var generated_280 = generated.isFlowPredicate; + var generated_281 = generated.isEnumBody; + var generated_282 = generated.isEnumMember; + var generated_283 = generated.isJSX; + var generated_284 = generated.isPrivate; + var generated_285 = generated.isTSTypeElement; + var generated_286 = generated.isTSType; + var generated_287 = generated.isTSBaseType; + var generated_288 = generated.isNumberLiteral; + var generated_289 = generated.isRegexLiteral; + var generated_290 = generated.isRestProperty; + var generated_291 = generated.isSpreadProperty; + + var matchesPattern_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = matchesPattern; + + + + function matchesPattern(member, match, allowPartial) { + if (!(0, generated.isMemberExpression)(member)) return false; + const parts = Array.isArray(match) ? match : match.split("."); + const nodes = []; + let node; + + for (node = member; (0, generated.isMemberExpression)(node); node = node.object) { + nodes.push(node.property); + } + + nodes.push(node); + if (nodes.length < parts.length) return false; + if (!allowPartial && nodes.length > parts.length) return false; + + for (let i = 0, j = nodes.length - 1; i < parts.length; i++, j--) { + const node = nodes[j]; + let value; + + if ((0, generated.isIdentifier)(node)) { + value = node.name; + } else if ((0, generated.isStringLiteral)(node)) { + value = node.value; + } else { + return false; + } + + if (parts[i] !== value) return false; + } + + return true; + } + }); + + unwrapExports(matchesPattern_1); + + var buildMatchMemberExpression_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = buildMatchMemberExpression; + + var _matchesPattern = _interopRequireDefault(matchesPattern_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function buildMatchMemberExpression(match, allowPartial) { + const parts = match.split("."); + return member => (0, _matchesPattern.default)(member, parts, allowPartial); + } + }); + + unwrapExports(buildMatchMemberExpression_1); + + var isReactComponent_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = void 0; + + var _buildMatchMemberExpression = _interopRequireDefault(buildMatchMemberExpression_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + const isReactComponent = (0, _buildMatchMemberExpression.default)("React.Component"); + var _default = isReactComponent; + exports.default = _default; + }); + + unwrapExports(isReactComponent_1); + + var isCompatTag_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = isCompatTag; + + function isCompatTag(tagName) { + return !!tagName && /^[a-z]/.test(tagName); + } + }); + + unwrapExports(isCompatTag_1); + + /** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + + var _listCacheClear = listCacheClear; + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + var eq_1 = eq; + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq_1(array[length][0], key)) { + return length; + } + } + return -1; + } + + var _assocIndexOf = assocIndexOf; + + /** Used for built-in method references. */ + var arrayProto = Array.prototype; + + /** Built-in value references. */ + var splice = arrayProto.splice; + + /** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function listCacheDelete(key) { + var data = this.__data__, + index = _assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + + var _listCacheDelete = listCacheDelete; + + /** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function listCacheGet(key) { + var data = this.__data__, + index = _assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; + } + + var _listCacheGet = listCacheGet; + + /** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function listCacheHas(key) { + return _assocIndexOf(this.__data__, key) > -1; + } + + var _listCacheHas = listCacheHas; + + /** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + function listCacheSet(key, value) { + var data = this.__data__, + index = _assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + + var _listCacheSet = listCacheSet; + + /** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = _listCacheClear; + ListCache.prototype['delete'] = _listCacheDelete; + ListCache.prototype.get = _listCacheGet; + ListCache.prototype.has = _listCacheHas; + ListCache.prototype.set = _listCacheSet; + + var _ListCache = ListCache; + + /** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + function stackClear() { + this.__data__ = new _ListCache; + this.size = 0; + } + + var _stackClear = stackClear; + + /** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; + } + + var _stackDelete = stackDelete; + + /** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function stackGet(key) { + return this.__data__.get(key); + } + + var _stackGet = stackGet; + + /** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function stackHas(key) { + return this.__data__.has(key); + } + + var _stackHas = stackHas; + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; + + var _freeGlobal = freeGlobal; + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + + /** Used as a reference to the global object. */ + var root = _freeGlobal || freeSelf || Function('return this')(); + + var _root = root; + + /** Built-in value references. */ + var Symbol$1 = _root.Symbol; + + var _Symbol = Symbol$1; + + /** Used for built-in method references. */ + var objectProto = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var nativeObjectToString = objectProto.toString; + + /** Built-in value references. */ + var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined; + + /** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; + } + + var _getRawTag = getRawTag; + + /** Used for built-in method references. */ + var objectProto$1 = Object.prototype; + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var nativeObjectToString$1 = objectProto$1.toString; + + /** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + function objectToString(value) { + return nativeObjectToString$1.call(value); + } + + var _objectToString = objectToString; + + /** `Object#toString` result references. */ + var nullTag = '[object Null]', + undefinedTag = '[object Undefined]'; + + /** Built-in value references. */ + var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined; + + /** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag$1 && symToStringTag$1 in Object(value)) + ? _getRawTag(value) + : _objectToString(value); + } + + var _baseGetTag = baseGetTag; + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + var isObject_1 = isObject; + + /** `Object#toString` result references. */ + var asyncTag = '[object AsyncFunction]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + proxyTag = '[object Proxy]'; + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject_1(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = _baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + } + + var isFunction_1 = isFunction; + + /** Used to detect overreaching core-js shims. */ + var coreJsData = _root['__core-js_shared__']; + + var _coreJsData = coreJsData; + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } + + var _isMasked = isMasked; + + /** Used for built-in method references. */ + var funcProto = Function.prototype; + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } + + var _toSource = toSource; + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used for built-in method references. */ + var funcProto$1 = Function.prototype, + objectProto$2 = Object.prototype; + + /** Used to resolve the decompiled source of functions. */ + var funcToString$1 = funcProto$1.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty$1 = objectProto$2.hasOwnProperty; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString$1.call(hasOwnProperty$1).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject_1(value) || _isMasked(value)) { + return false; + } + var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor; + return pattern.test(_toSource(value)); + } + + var _baseIsNative = baseIsNative; + + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } + + var _getValue = getValue; + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = _getValue(object, key); + return _baseIsNative(value) ? value : undefined; + } + + var _getNative = getNative; + + /* Built-in method references that are verified to be native. */ + var Map$1 = _getNative(_root, 'Map'); + + var _Map = Map$1; + + /* Built-in method references that are verified to be native. */ + var nativeCreate = _getNative(Object, 'create'); + + var _nativeCreate = nativeCreate; + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = _nativeCreate ? _nativeCreate(null) : {}; + this.size = 0; + } + + var _hashClear = hashClear; + + /** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + + var _hashDelete = hashDelete; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used for built-in method references. */ + var objectProto$3 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$2 = objectProto$3.hasOwnProperty; + + /** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function hashGet(key) { + var data = this.__data__; + if (_nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty$2.call(data, key) ? data[key] : undefined; + } + + var _hashGet = hashGet; + + /** Used for built-in method references. */ + var objectProto$4 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$3 = objectProto$4.hasOwnProperty; + + /** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function hashHas(key) { + var data = this.__data__; + return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$3.call(data, key); + } + + var _hashHas = hashHas; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; + + /** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; + return this; + } + + var _hashSet = hashSet; + + /** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + // Add methods to `Hash`. + Hash.prototype.clear = _hashClear; + Hash.prototype['delete'] = _hashDelete; + Hash.prototype.get = _hashGet; + Hash.prototype.has = _hashHas; + Hash.prototype.set = _hashSet; + + var _Hash = Hash; + + /** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new _Hash, + 'map': new (_Map || _ListCache), + 'string': new _Hash + }; + } + + var _mapCacheClear = mapCacheClear; + + /** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + var _isKeyable = isKeyable; + + /** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + function getMapData(map, key) { + var data = map.__data__; + return _isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; + } + + var _getMapData = getMapData; + + /** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function mapCacheDelete(key) { + var result = _getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; + } + + var _mapCacheDelete = mapCacheDelete; + + /** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return _getMapData(this, key).get(key); + } + + var _mapCacheGet = mapCacheGet; + + /** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapCacheHas(key) { + return _getMapData(this, key).has(key); + } + + var _mapCacheHas = mapCacheHas; + + /** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + function mapCacheSet(key, value) { + var data = _getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + + var _mapCacheSet = mapCacheSet; + + /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = _mapCacheClear; + MapCache.prototype['delete'] = _mapCacheDelete; + MapCache.prototype.get = _mapCacheGet; + MapCache.prototype.has = _mapCacheHas; + MapCache.prototype.set = _mapCacheSet; + + var _MapCache = MapCache; + + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof _ListCache) { + var pairs = data.__data__; + if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new _MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + + var _stackSet = stackSet; + + /** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Stack(entries) { + var data = this.__data__ = new _ListCache(entries); + this.size = data.size; + } + + // Add methods to `Stack`. + Stack.prototype.clear = _stackClear; + Stack.prototype['delete'] = _stackDelete; + Stack.prototype.get = _stackGet; + Stack.prototype.has = _stackHas; + Stack.prototype.set = _stackSet; + + var _Stack = Stack; + + /** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEach(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; + } + + var _arrayEach = arrayEach; + + var defineProperty = (function() { + try { + var func = _getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); + + var _defineProperty = defineProperty; + + /** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function baseAssignValue(object, key, value) { + if (key == '__proto__' && _defineProperty) { + _defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } + } + + var _baseAssignValue = baseAssignValue; + + /** Used for built-in method references. */ + var objectProto$5 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$4 = objectProto$5.hasOwnProperty; + + /** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty$4.call(object, key) && eq_1(objValue, value)) || + (value === undefined && !(key in object))) { + _baseAssignValue(object, key, value); + } + } + + var _assignValue = assignValue; + + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + _baseAssignValue(object, key, newValue); + } else { + _assignValue(object, key, newValue); + } + } + return object; + } + + var _copyObject = copyObject; + + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + + var _baseTimes = baseTimes; + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == 'object'; + } + + var isObjectLike_1 = isObjectLike; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]'; + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + function baseIsArguments(value) { + return isObjectLike_1(value) && _baseGetTag(value) == argsTag; + } + + var _baseIsArguments = baseIsArguments; + + /** Used for built-in method references. */ + var objectProto$6 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$5 = objectProto$6.hasOwnProperty; + + /** Built-in value references. */ + var propertyIsEnumerable = objectProto$6.propertyIsEnumerable; + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) { + return isObjectLike_1(value) && hasOwnProperty$5.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; + + var isArguments_1 = isArguments; + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; + + var isArray_1 = isArray; + + /** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ + function stubFalse() { + return false; + } + + var stubFalse_1 = stubFalse; + + var isBuffer_1 = createCommonjsModule(function (module, exports) { + /** Detect free variable `exports`. */ + var freeExports = exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Built-in value references. */ + var Buffer = moduleExports ? _root.Buffer : undefined; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; + + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse_1; + + module.exports = isBuffer; + }); + + /** Used as references for various `Number` constants. */ + var MAX_SAFE_INTEGER = 9007199254740991; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); + } + + var _isIndex = isIndex; + + /** Used as references for various `Number` constants. */ + var MAX_SAFE_INTEGER$1 = 9007199254740991; + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; + } + + var isLength_1 = isLength; + + /** `Object#toString` result references. */ + var argsTag$1 = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag$1 = '[object Function]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + weakMapTag = '[object WeakMap]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike_1(value) && + isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)]; + } + + var _baseIsTypedArray = baseIsTypedArray; + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + + var _baseUnary = baseUnary; + + var _nodeUtil = createCommonjsModule(function (module, exports) { + /** Detect free variable `exports`. */ + var freeExports = exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && _freeGlobal.process; + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule && freeModule.require && freeModule.require('util').types; + + if (types) { + return types; + } + + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); + + module.exports = nodeUtil; + }); + + /* Node.js helper references. */ + var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray; + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray; + + var isTypedArray_1 = isTypedArray; + + /** Used for built-in method references. */ + var objectProto$7 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$6 = objectProto$7.hasOwnProperty; + + /** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray_1(value), + isArg = !isArr && isArguments_1(value), + isBuff = !isArr && !isArg && isBuffer_1(value), + isType = !isArr && !isArg && !isBuff && isTypedArray_1(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? _baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty$6.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + _isIndex(key, length) + ))) { + result.push(key); + } + } + return result; + } + + var _arrayLikeKeys = arrayLikeKeys; + + /** Used for built-in method references. */ + var objectProto$8 = Object.prototype; + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$8; + + return value === proto; + } + + var _isPrototype = isPrototype; + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + var _overArg = overArg; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeKeys = _overArg(Object.keys, Object); + + var _nativeKeys = nativeKeys; + + /** Used for built-in method references. */ + var objectProto$9 = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$7 = objectProto$9.hasOwnProperty; + + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!_isPrototype(object)) { + return _nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty$7.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + var _baseKeys = baseKeys; + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength_1(value.length) && !isFunction_1(value); + } + + var isArrayLike_1 = isArrayLike; + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object); + } + + var keys_1 = keys; + + /** + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssign(object, source) { + return object && _copyObject(source, keys_1(source), object); + } + + var _baseAssign = baseAssign; + + /** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + + var _nativeKeysIn = nativeKeysIn; + + /** Used for built-in method references. */ + var objectProto$a = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$8 = objectProto$a.hasOwnProperty; + + /** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeysIn(object) { + if (!isObject_1(object)) { + return _nativeKeysIn(object); + } + var isProto = _isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty$8.call(object, key)))) { + result.push(key); + } + } + return result; + } + + var _baseKeysIn = baseKeysIn; + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + function keysIn(object) { + return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object); + } + + var keysIn_1 = keysIn; + + /** + * The base implementation of `_.assignIn` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssignIn(object, source) { + return object && _copyObject(source, keysIn_1(source), object); + } + + var _baseAssignIn = baseAssignIn; + + var _cloneBuffer = createCommonjsModule(function (module, exports) { + /** Detect free variable `exports`. */ + var freeExports = exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Built-in value references. */ + var Buffer = moduleExports ? _root.Buffer : undefined, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; + + /** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; + } + + module.exports = cloneBuffer; + }); + + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } + + var _copyArray = copyArray; + + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + + var _arrayFilter = arrayFilter; + + /** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ + function stubArray() { + return []; + } + + var stubArray_1 = stubArray; + + /** Used for built-in method references. */ + var objectProto$b = Object.prototype; + + /** Built-in value references. */ + var propertyIsEnumerable$1 = objectProto$b.propertyIsEnumerable; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeGetSymbols = Object.getOwnPropertySymbols; + + /** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = !nativeGetSymbols ? stubArray_1 : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return _arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable$1.call(object, symbol); + }); + }; + + var _getSymbols = getSymbols; + + /** + * Copies own symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ + function copySymbols(source, object) { + return _copyObject(source, _getSymbols(source), object); + } + + var _copySymbols = copySymbols; + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + + var _arrayPush = arrayPush; + + /** Built-in value references. */ + var getPrototype = _overArg(Object.getPrototypeOf, Object); + + var _getPrototype = getPrototype; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeGetSymbols$1 = Object.getOwnPropertySymbols; + + /** + * Creates an array of the own and inherited enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbolsIn = !nativeGetSymbols$1 ? stubArray_1 : function(object) { + var result = []; + while (object) { + _arrayPush(result, _getSymbols(object)); + object = _getPrototype(object); + } + return result; + }; + + var _getSymbolsIn = getSymbolsIn; + + /** + * Copies own and inherited symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ + function copySymbolsIn(source, object) { + return _copyObject(source, _getSymbolsIn(source), object); + } + + var _copySymbolsIn = copySymbolsIn; + + /** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object)); + } + + var _baseGetAllKeys = baseGetAllKeys; + + /** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeys(object) { + return _baseGetAllKeys(object, keys_1, _getSymbols); + } + + var _getAllKeys = getAllKeys; + + /** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeysIn(object) { + return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn); + } + + var _getAllKeysIn = getAllKeysIn; + + /* Built-in method references that are verified to be native. */ + var DataView$1 = _getNative(_root, 'DataView'); + + var _DataView = DataView$1; + + /* Built-in method references that are verified to be native. */ + var Promise$1 = _getNative(_root, 'Promise'); + + var _Promise = Promise$1; + + /* Built-in method references that are verified to be native. */ + var Set$1 = _getNative(_root, 'Set'); + + var _Set = Set$1; + + /* Built-in method references that are verified to be native. */ + var WeakMap$1 = _getNative(_root, 'WeakMap'); + + var _WeakMap = WeakMap$1; + + /** `Object#toString` result references. */ + var mapTag$1 = '[object Map]', + objectTag$1 = '[object Object]', + promiseTag = '[object Promise]', + setTag$1 = '[object Set]', + weakMapTag$1 = '[object WeakMap]'; + + var dataViewTag$1 = '[object DataView]'; + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = _toSource(_DataView), + mapCtorString = _toSource(_Map), + promiseCtorString = _toSource(_Promise), + setCtorString = _toSource(_Set), + weakMapCtorString = _toSource(_WeakMap); + + /** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = _baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$1) || + (_Map && getTag(new _Map) != mapTag$1) || + (_Promise && getTag(_Promise.resolve()) != promiseTag) || + (_Set && getTag(new _Set) != setTag$1) || + (_WeakMap && getTag(new _WeakMap) != weakMapTag$1)) { + getTag = function(value) { + var result = _baseGetTag(value), + Ctor = result == objectTag$1 ? value.constructor : undefined, + ctorString = Ctor ? _toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag$1; + case mapCtorString: return mapTag$1; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag$1; + case weakMapCtorString: return weakMapTag$1; + } + } + return result; + }; + } + + var _getTag = getTag; + + /** Used for built-in method references. */ + var objectProto$c = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$9 = objectProto$c.hasOwnProperty; + + /** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ + function initCloneArray(array) { + var length = array.length, + result = new array.constructor(length); + + // Add properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty$9.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; + } + + var _initCloneArray = initCloneArray; + + /** Built-in value references. */ + var Uint8Array$1 = _root.Uint8Array; + + var _Uint8Array = Uint8Array$1; + + /** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ + function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new _Uint8Array(result).set(new _Uint8Array(arrayBuffer)); + return result; + } + + var _cloneArrayBuffer = cloneArrayBuffer; + + /** + * Creates a clone of `dataView`. + * + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */ + function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); + } + + var _cloneDataView = cloneDataView; + + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; + + /** + * Creates a clone of `regexp`. + * + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */ + function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; + } + + var _cloneRegExp = cloneRegExp; + + /** Used to convert symbols to primitives and strings. */ + var symbolProto = _Symbol ? _Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; + + /** + * Creates a clone of the `symbol` object. + * + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */ + function cloneSymbol(symbol) { + return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; + } + + var _cloneSymbol = cloneSymbol; + + /** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } + + var _cloneTypedArray = cloneTypedArray; + + /** `Object#toString` result references. */ + var boolTag$1 = '[object Boolean]', + dateTag$1 = '[object Date]', + mapTag$2 = '[object Map]', + numberTag$1 = '[object Number]', + regexpTag$1 = '[object RegExp]', + setTag$2 = '[object Set]', + stringTag$1 = '[object String]', + symbolTag = '[object Symbol]'; + + var arrayBufferTag$1 = '[object ArrayBuffer]', + dataViewTag$2 = '[object DataView]', + float32Tag$1 = '[object Float32Array]', + float64Tag$1 = '[object Float64Array]', + int8Tag$1 = '[object Int8Array]', + int16Tag$1 = '[object Int16Array]', + int32Tag$1 = '[object Int32Array]', + uint8Tag$1 = '[object Uint8Array]', + uint8ClampedTag$1 = '[object Uint8ClampedArray]', + uint16Tag$1 = '[object Uint16Array]', + uint32Tag$1 = '[object Uint32Array]'; + + /** + * Initializes an object clone based on its `toStringTag`. + * + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. + * + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneByTag(object, tag, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag$1: + return _cloneArrayBuffer(object); + + case boolTag$1: + case dateTag$1: + return new Ctor(+object); + + case dataViewTag$2: + return _cloneDataView(object, isDeep); + + case float32Tag$1: case float64Tag$1: + case int8Tag$1: case int16Tag$1: case int32Tag$1: + case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1: + return _cloneTypedArray(object, isDeep); + + case mapTag$2: + return new Ctor; + + case numberTag$1: + case stringTag$1: + return new Ctor(object); + + case regexpTag$1: + return _cloneRegExp(object); + + case setTag$2: + return new Ctor; + + case symbolTag: + return _cloneSymbol(object); + } + } + + var _initCloneByTag = initCloneByTag; + + /** Built-in value references. */ + var objectCreate = Object.create; + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ + var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject_1(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; + }()); + + var _baseCreate = baseCreate; + + /** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneObject(object) { + return (typeof object.constructor == 'function' && !_isPrototype(object)) + ? _baseCreate(_getPrototype(object)) + : {}; + } + + var _initCloneObject = initCloneObject; + + /** `Object#toString` result references. */ + var mapTag$3 = '[object Map]'; + + /** + * The base implementation of `_.isMap` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + */ + function baseIsMap(value) { + return isObjectLike_1(value) && _getTag(value) == mapTag$3; + } + + var _baseIsMap = baseIsMap; + + /* Node.js helper references. */ + var nodeIsMap = _nodeUtil && _nodeUtil.isMap; + + /** + * Checks if `value` is classified as a `Map` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + * @example + * + * _.isMap(new Map); + * // => true + * + * _.isMap(new WeakMap); + * // => false + */ + var isMap = nodeIsMap ? _baseUnary(nodeIsMap) : _baseIsMap; + + var isMap_1 = isMap; + + /** `Object#toString` result references. */ + var setTag$3 = '[object Set]'; + + /** + * The base implementation of `_.isSet` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + */ + function baseIsSet(value) { + return isObjectLike_1(value) && _getTag(value) == setTag$3; + } + + var _baseIsSet = baseIsSet; + + /* Node.js helper references. */ + var nodeIsSet = _nodeUtil && _nodeUtil.isSet; + + /** + * Checks if `value` is classified as a `Set` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + * @example + * + * _.isSet(new Set); + * // => true + * + * _.isSet(new WeakSet); + * // => false + */ + var isSet = nodeIsSet ? _baseUnary(nodeIsSet) : _baseIsSet; + + var isSet_1 = isSet; + + /** Used to compose bitmasks for cloning. */ + var CLONE_DEEP_FLAG = 1, + CLONE_FLAT_FLAG = 2, + CLONE_SYMBOLS_FLAG = 4; + + /** `Object#toString` result references. */ + var argsTag$2 = '[object Arguments]', + arrayTag$1 = '[object Array]', + boolTag$2 = '[object Boolean]', + dateTag$2 = '[object Date]', + errorTag$1 = '[object Error]', + funcTag$2 = '[object Function]', + genTag$1 = '[object GeneratorFunction]', + mapTag$4 = '[object Map]', + numberTag$2 = '[object Number]', + objectTag$2 = '[object Object]', + regexpTag$2 = '[object RegExp]', + setTag$4 = '[object Set]', + stringTag$2 = '[object String]', + symbolTag$1 = '[object Symbol]', + weakMapTag$2 = '[object WeakMap]'; + + var arrayBufferTag$2 = '[object ArrayBuffer]', + dataViewTag$3 = '[object DataView]', + float32Tag$2 = '[object Float32Array]', + float64Tag$2 = '[object Float64Array]', + int8Tag$2 = '[object Int8Array]', + int16Tag$2 = '[object Int16Array]', + int32Tag$2 = '[object Int32Array]', + uint8Tag$2 = '[object Uint8Array]', + uint8ClampedTag$2 = '[object Uint8ClampedArray]', + uint16Tag$2 = '[object Uint16Array]', + uint32Tag$2 = '[object Uint32Array]'; + + /** Used to identify `toStringTag` values supported by `_.clone`. */ + var cloneableTags = {}; + cloneableTags[argsTag$2] = cloneableTags[arrayTag$1] = + cloneableTags[arrayBufferTag$2] = cloneableTags[dataViewTag$3] = + cloneableTags[boolTag$2] = cloneableTags[dateTag$2] = + cloneableTags[float32Tag$2] = cloneableTags[float64Tag$2] = + cloneableTags[int8Tag$2] = cloneableTags[int16Tag$2] = + cloneableTags[int32Tag$2] = cloneableTags[mapTag$4] = + cloneableTags[numberTag$2] = cloneableTags[objectTag$2] = + cloneableTags[regexpTag$2] = cloneableTags[setTag$4] = + cloneableTags[stringTag$2] = cloneableTags[symbolTag$1] = + cloneableTags[uint8Tag$2] = cloneableTags[uint8ClampedTag$2] = + cloneableTags[uint16Tag$2] = cloneableTags[uint32Tag$2] = true; + cloneableTags[errorTag$1] = cloneableTags[funcTag$2] = + cloneableTags[weakMapTag$2] = false; + + /** + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} bitmask The bitmask flags. + * 1 - Deep clone + * 2 - Flatten inherited properties + * 4 - Clone symbols + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. + */ + function baseClone(value, bitmask, customizer, key, object, stack) { + var result, + isDeep = bitmask & CLONE_DEEP_FLAG, + isFlat = bitmask & CLONE_FLAT_FLAG, + isFull = bitmask & CLONE_SYMBOLS_FLAG; + + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject_1(value)) { + return value; + } + var isArr = isArray_1(value); + if (isArr) { + result = _initCloneArray(value); + if (!isDeep) { + return _copyArray(value, result); + } + } else { + var tag = _getTag(value), + isFunc = tag == funcTag$2 || tag == genTag$1; + + if (isBuffer_1(value)) { + return _cloneBuffer(value, isDeep); + } + if (tag == objectTag$2 || tag == argsTag$2 || (isFunc && !object)) { + result = (isFlat || isFunc) ? {} : _initCloneObject(value); + if (!isDeep) { + return isFlat + ? _copySymbolsIn(value, _baseAssignIn(result, value)) + : _copySymbols(value, _baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = _initCloneByTag(value, tag, isDeep); + } + } + // Check for circular references and return its corresponding clone. + stack || (stack = new _Stack); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); + + if (isSet_1(value)) { + value.forEach(function(subValue) { + result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); + }); + } else if (isMap_1(value)) { + value.forEach(function(subValue, key) { + result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + } + + var keysFunc = isFull + ? (isFlat ? _getAllKeysIn : _getAllKeys) + : (isFlat ? keysIn_1 : keys_1); + + var props = isArr ? undefined : keysFunc(value); + _arrayEach(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; + } + // Recursively populate clone (susceptible to call stack limits). + _assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + return result; + } + + var _baseClone = baseClone; + + /** Used to compose bitmasks for cloning. */ + var CLONE_SYMBOLS_FLAG$1 = 4; + + /** + * Creates a shallow clone of `value`. + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); + * // => true + */ + function clone(value) { + return _baseClone(value, CLONE_SYMBOLS_FLAG$1); + } + + var clone_1 = clone; + + let fastProto = null; + + // Creates an object with permanently fast properties in V8. See Toon Verwaest's + // post https://medium.com/@tverwaes/setting-up-prototypes-in-v8-ec9c9491dfe2#5f62 + // for more details. Use %HasFastProperties(object) and the Node.js flag + // --allow-natives-syntax to check whether an object has fast properties. + function FastObject(o) { + // A prototype object will have "fast properties" enabled once it is checked + // against the inline property cache of a function, e.g. fastProto.property: + // https://github.com/v8/v8/blob/6.0.122/test/mjsunit/fast-prototype.js#L48-L63 + if (fastProto !== null && typeof fastProto.property) { + const result = fastProto; + fastProto = FastObject.prototype = null; + return result; + } + fastProto = FastObject.prototype = o == null ? Object.create(null) : o; + return new FastObject; + } + + // Initialize the inline property cache of FastObject + FastObject(); + + var toFastProperties = function toFastproperties(o) { + return FastObject(o); + }; + + var isType_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = isType; + + + + function isType(nodeType, targetType) { + if (nodeType === targetType) return true; + if (definitions.ALIAS_KEYS[targetType]) return false; + const aliases = definitions.FLIPPED_ALIAS_KEYS[targetType]; + + if (aliases) { + if (aliases[0] === nodeType) return true; + + for (const alias of aliases) { + if (nodeType === alias) return true; + } + } + + return false; + } + }); + + unwrapExports(isType_1); + + var isPlaceholderType_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = isPlaceholderType; + + + + function isPlaceholderType(placeholderType, targetType) { + if (placeholderType === targetType) return true; + const aliases = definitions.PLACEHOLDERS_ALIAS[placeholderType]; + + if (aliases) { + for (const alias of aliases) { + if (targetType === alias) return true; + } + } + + return false; + } + }); + + unwrapExports(isPlaceholderType_1); + + var is_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = is; + + var _shallowEqual = _interopRequireDefault(shallowEqual_1); + + var _isType = _interopRequireDefault(isType_1); + + var _isPlaceholderType = _interopRequireDefault(isPlaceholderType_1); + + + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function is(type, node, opts) { + if (!node) return false; + const matches = (0, _isType.default)(node.type, type); + + if (!matches) { + if (!opts && node.type === "Placeholder" && type in definitions.FLIPPED_ALIAS_KEYS) { + return (0, _isPlaceholderType.default)(node.expectedNode, type); + } + + return false; + } + + if (typeof opts === "undefined") { + return true; + } else { + return (0, _shallowEqual.default)(node, opts); + } + } + }); + + unwrapExports(is_1); + + var identifier = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.isIdentifierStart = isIdentifierStart; + exports.isIdentifierChar = isIdentifierChar; + exports.isIdentifierName = isIdentifierName; + let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; + let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; + const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); + const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); + nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; + const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8952, 286, 50, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938]; + const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; + + function isInAstralSet(code, set) { + let pos = 0x10000; + + for (let i = 0, length = set.length; i < length; i += 2) { + pos += set[i]; + if (pos > code) return false; + pos += set[i + 1]; + if (pos >= code) return true; + } + + return false; + } + + function isIdentifierStart(code) { + if (code < 65) return code === 36; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); + } + + return isInAstralSet(code, astralIdentifierStartCodes); + } + + function isIdentifierChar(code) { + if (code < 48) return code === 36; + if (code < 58) return true; + if (code < 65) return false; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); + } + + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); + } + + function isIdentifierName(name) { + let isFirst = true; + + for (let _i = 0, _Array$from = Array.from(name); _i < _Array$from.length; _i++) { + const char = _Array$from[_i]; + const cp = char.codePointAt(0); + + if (isFirst) { + if (!isIdentifierStart(cp)) { + return false; + } + + isFirst = false; + } else if (!isIdentifierChar(cp)) { + return false; + } + } + + return !isFirst; + } + }); + + unwrapExports(identifier); + var identifier_1 = identifier.isIdentifierStart; + var identifier_2 = identifier.isIdentifierChar; + var identifier_3 = identifier.isIdentifierName; + + var keyword = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.isReservedWord = isReservedWord; + exports.isStrictReservedWord = isStrictReservedWord; + exports.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord; + exports.isStrictBindReservedWord = isStrictBindReservedWord; + exports.isKeyword = isKeyword; + const reservedWords = { + keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], + strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], + strictBind: ["eval", "arguments"] + }; + const keywords = new Set(reservedWords.keyword); + const reservedWordsStrictSet = new Set(reservedWords.strict); + const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); + + function isReservedWord(word, inModule) { + return inModule && word === "await" || word === "enum"; + } + + function isStrictReservedWord(word, inModule) { + return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); + } + + function isStrictBindOnlyReservedWord(word) { + return reservedWordsStrictBindSet.has(word); + } + + function isStrictBindReservedWord(word, inModule) { + return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); + } + + function isKeyword(word) { + return keywords.has(word); + } + }); + + unwrapExports(keyword); + var keyword_1 = keyword.isReservedWord; + var keyword_2 = keyword.isStrictReservedWord; + var keyword_3 = keyword.isStrictBindOnlyReservedWord; + var keyword_4 = keyword.isStrictBindReservedWord; + var keyword_5 = keyword.isKeyword; + + var lib = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + Object.defineProperty(exports, "isIdentifierName", { + enumerable: true, + get: function () { + return identifier.isIdentifierName; + } + }); + Object.defineProperty(exports, "isIdentifierChar", { + enumerable: true, + get: function () { + return identifier.isIdentifierChar; + } + }); + Object.defineProperty(exports, "isIdentifierStart", { + enumerable: true, + get: function () { + return identifier.isIdentifierStart; + } + }); + Object.defineProperty(exports, "isReservedWord", { + enumerable: true, + get: function () { + return keyword.isReservedWord; + } + }); + Object.defineProperty(exports, "isStrictBindOnlyReservedWord", { + enumerable: true, + get: function () { + return keyword.isStrictBindOnlyReservedWord; + } + }); + Object.defineProperty(exports, "isStrictBindReservedWord", { + enumerable: true, + get: function () { + return keyword.isStrictBindReservedWord; + } + }); + Object.defineProperty(exports, "isStrictReservedWord", { + enumerable: true, + get: function () { + return keyword.isStrictReservedWord; + } + }); + Object.defineProperty(exports, "isKeyword", { + enumerable: true, + get: function () { + return keyword.isKeyword; + } + }); + }); + + unwrapExports(lib); + + var isValidIdentifier_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = isValidIdentifier; + + + + function isValidIdentifier(name, reserved = true) { + if (typeof name !== "string") return false; + + if (reserved) { + if ((0, lib.isKeyword)(name) || (0, lib.isStrictReservedWord)(name)) { + return false; + } else if (name === "await") { + return false; + } + } + + return (0, lib.isIdentifierName)(name); + } + }); + + unwrapExports(isValidIdentifier_1); + + var constants = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.NOT_LOCAL_BINDING = exports.BLOCK_SCOPED_SYMBOL = exports.INHERIT_KEYS = exports.UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = exports.ASSIGNMENT_OPERATORS = exports.BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = exports.UPDATE_OPERATORS = exports.LOGICAL_OPERATORS = exports.COMMENT_KEYS = exports.FOR_INIT_KEYS = exports.FLATTENABLE_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = void 0; + const STATEMENT_OR_BLOCK_KEYS = ["consequent", "body", "alternate"]; + exports.STATEMENT_OR_BLOCK_KEYS = STATEMENT_OR_BLOCK_KEYS; + const FLATTENABLE_KEYS = ["body", "expressions"]; + exports.FLATTENABLE_KEYS = FLATTENABLE_KEYS; + const FOR_INIT_KEYS = ["left", "init"]; + exports.FOR_INIT_KEYS = FOR_INIT_KEYS; + const COMMENT_KEYS = ["leadingComments", "trailingComments", "innerComments"]; + exports.COMMENT_KEYS = COMMENT_KEYS; + const LOGICAL_OPERATORS = ["||", "&&", "??"]; + exports.LOGICAL_OPERATORS = LOGICAL_OPERATORS; + const UPDATE_OPERATORS = ["++", "--"]; + exports.UPDATE_OPERATORS = UPDATE_OPERATORS; + const BOOLEAN_NUMBER_BINARY_OPERATORS = [">", "<", ">=", "<="]; + exports.BOOLEAN_NUMBER_BINARY_OPERATORS = BOOLEAN_NUMBER_BINARY_OPERATORS; + const EQUALITY_BINARY_OPERATORS = ["==", "===", "!=", "!=="]; + exports.EQUALITY_BINARY_OPERATORS = EQUALITY_BINARY_OPERATORS; + const COMPARISON_BINARY_OPERATORS = [...EQUALITY_BINARY_OPERATORS, "in", "instanceof"]; + exports.COMPARISON_BINARY_OPERATORS = COMPARISON_BINARY_OPERATORS; + const BOOLEAN_BINARY_OPERATORS = [...COMPARISON_BINARY_OPERATORS, ...BOOLEAN_NUMBER_BINARY_OPERATORS]; + exports.BOOLEAN_BINARY_OPERATORS = BOOLEAN_BINARY_OPERATORS; + const NUMBER_BINARY_OPERATORS = ["-", "/", "%", "*", "**", "&", "|", ">>", ">>>", "<<", "^"]; + exports.NUMBER_BINARY_OPERATORS = NUMBER_BINARY_OPERATORS; + const BINARY_OPERATORS = ["+", ...NUMBER_BINARY_OPERATORS, ...BOOLEAN_BINARY_OPERATORS]; + exports.BINARY_OPERATORS = BINARY_OPERATORS; + const ASSIGNMENT_OPERATORS = ["=", "+=", ...NUMBER_BINARY_OPERATORS.map(op => op + "="), ...LOGICAL_OPERATORS.map(op => op + "=")]; + exports.ASSIGNMENT_OPERATORS = ASSIGNMENT_OPERATORS; + const BOOLEAN_UNARY_OPERATORS = ["delete", "!"]; + exports.BOOLEAN_UNARY_OPERATORS = BOOLEAN_UNARY_OPERATORS; + const NUMBER_UNARY_OPERATORS = ["+", "-", "~"]; + exports.NUMBER_UNARY_OPERATORS = NUMBER_UNARY_OPERATORS; + const STRING_UNARY_OPERATORS = ["typeof"]; + exports.STRING_UNARY_OPERATORS = STRING_UNARY_OPERATORS; + const UNARY_OPERATORS = ["void", "throw", ...BOOLEAN_UNARY_OPERATORS, ...NUMBER_UNARY_OPERATORS, ...STRING_UNARY_OPERATORS]; + exports.UNARY_OPERATORS = UNARY_OPERATORS; + const INHERIT_KEYS = { + optional: ["typeAnnotation", "typeParameters", "returnType"], + force: ["start", "loc", "end"] + }; + exports.INHERIT_KEYS = INHERIT_KEYS; + const BLOCK_SCOPED_SYMBOL = Symbol.for("var used to be block scoped"); + exports.BLOCK_SCOPED_SYMBOL = BLOCK_SCOPED_SYMBOL; + const NOT_LOCAL_BINDING = Symbol.for("should not be considered a local binding"); + exports.NOT_LOCAL_BINDING = NOT_LOCAL_BINDING; + }); + + unwrapExports(constants); + var constants_1 = constants.NOT_LOCAL_BINDING; + var constants_2 = constants.BLOCK_SCOPED_SYMBOL; + var constants_3 = constants.INHERIT_KEYS; + var constants_4 = constants.UNARY_OPERATORS; + var constants_5 = constants.STRING_UNARY_OPERATORS; + var constants_6 = constants.NUMBER_UNARY_OPERATORS; + var constants_7 = constants.BOOLEAN_UNARY_OPERATORS; + var constants_8 = constants.ASSIGNMENT_OPERATORS; + var constants_9 = constants.BINARY_OPERATORS; + var constants_10 = constants.NUMBER_BINARY_OPERATORS; + var constants_11 = constants.BOOLEAN_BINARY_OPERATORS; + var constants_12 = constants.COMPARISON_BINARY_OPERATORS; + var constants_13 = constants.EQUALITY_BINARY_OPERATORS; + var constants_14 = constants.BOOLEAN_NUMBER_BINARY_OPERATORS; + var constants_15 = constants.UPDATE_OPERATORS; + var constants_16 = constants.LOGICAL_OPERATORS; + var constants_17 = constants.COMMENT_KEYS; + var constants_18 = constants.FOR_INIT_KEYS; + var constants_19 = constants.FLATTENABLE_KEYS; + var constants_20 = constants.STATEMENT_OR_BLOCK_KEYS; + + var validate_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = validate; + exports.validateField = validateField; + exports.validateChild = validateChild; + + + + function validate(node, key, val) { + if (!node) return; + const fields = definitions.NODE_FIELDS[node.type]; + if (!fields) return; + const field = fields[key]; + validateField(node, key, val, field); + validateChild(node, key, val); + } + + function validateField(node, key, val, field) { + if (!(field == null ? void 0 : field.validate)) return; + if (field.optional && val == null) return; + field.validate(node, key, val); + } + + function validateChild(node, key, val) { + if (val == null) return; + const validate = definitions.NODE_PARENT_VALIDATIONS[val.type]; + if (!validate) return; + validate(node, key, val); + } + }); + + unwrapExports(validate_1); + var validate_2 = validate_1.validateField; + var validate_3 = validate_1.validateChild; + + var utils = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.validate = validate; + exports.typeIs = typeIs; + exports.validateType = validateType; + exports.validateOptional = validateOptional; + exports.validateOptionalType = validateOptionalType; + exports.arrayOf = arrayOf; + exports.arrayOfType = arrayOfType; + exports.validateArrayOfType = validateArrayOfType; + exports.assertEach = assertEach; + exports.assertOneOf = assertOneOf; + exports.assertNodeType = assertNodeType; + exports.assertNodeOrValueType = assertNodeOrValueType; + exports.assertValueType = assertValueType; + exports.assertShape = assertShape; + exports.assertOptionalChainStart = assertOptionalChainStart; + exports.chain = chain; + exports.default = defineType; + exports.NODE_PARENT_VALIDATIONS = exports.DEPRECATED_KEYS = exports.BUILDER_KEYS = exports.NODE_FIELDS = exports.FLIPPED_ALIAS_KEYS = exports.ALIAS_KEYS = exports.VISITOR_KEYS = void 0; + + var _is = _interopRequireDefault(is_1); + + + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + const VISITOR_KEYS = {}; + exports.VISITOR_KEYS = VISITOR_KEYS; + const ALIAS_KEYS = {}; + exports.ALIAS_KEYS = ALIAS_KEYS; + const FLIPPED_ALIAS_KEYS = {}; + exports.FLIPPED_ALIAS_KEYS = FLIPPED_ALIAS_KEYS; + const NODE_FIELDS = {}; + exports.NODE_FIELDS = NODE_FIELDS; + const BUILDER_KEYS = {}; + exports.BUILDER_KEYS = BUILDER_KEYS; + const DEPRECATED_KEYS = {}; + exports.DEPRECATED_KEYS = DEPRECATED_KEYS; + const NODE_PARENT_VALIDATIONS = {}; + exports.NODE_PARENT_VALIDATIONS = NODE_PARENT_VALIDATIONS; + + function getType(val) { + if (Array.isArray(val)) { + return "array"; + } else if (val === null) { + return "null"; + } else { + return typeof val; + } + } + + function validate(validate) { + return { + validate + }; + } + + function typeIs(typeName) { + return typeof typeName === "string" ? assertNodeType(typeName) : assertNodeType(...typeName); + } + + function validateType(typeName) { + return validate(typeIs(typeName)); + } + + function validateOptional(validate) { + return { + validate, + optional: true + }; + } + + function validateOptionalType(typeName) { + return { + validate: typeIs(typeName), + optional: true + }; + } + + function arrayOf(elementType) { + return chain(assertValueType("array"), assertEach(elementType)); + } + + function arrayOfType(typeName) { + return arrayOf(typeIs(typeName)); + } + + function validateArrayOfType(typeName) { + return validate(arrayOfType(typeName)); + } + + function assertEach(callback) { + function validator(node, key, val) { + if (!Array.isArray(val)) return; + + for (let i = 0; i < val.length; i++) { + const subkey = `${key}[${i}]`; + const v = val[i]; + callback(node, subkey, v); + if (process.env.BABEL_TYPES_8_BREAKING) (0, validate_1.validateChild)(node, subkey, v); + } + } + + validator.each = callback; + return validator; + } + + function assertOneOf(...values) { + function validate(node, key, val) { + if (values.indexOf(val) < 0) { + throw new TypeError(`Property ${key} expected value to be one of ${JSON.stringify(values)} but got ${JSON.stringify(val)}`); + } + } + + validate.oneOf = values; + return validate; + } + + function assertNodeType(...types) { + function validate(node, key, val) { + for (const type of types) { + if ((0, _is.default)(type, val)) { + (0, validate_1.validateChild)(node, key, val); + return; + } + } + + throw new TypeError(`Property ${key} of ${node.type} expected node to be of a type ${JSON.stringify(types)} but instead got ${JSON.stringify(val == null ? void 0 : val.type)}`); + } + + validate.oneOfNodeTypes = types; + return validate; + } + + function assertNodeOrValueType(...types) { + function validate(node, key, val) { + for (const type of types) { + if (getType(val) === type || (0, _is.default)(type, val)) { + (0, validate_1.validateChild)(node, key, val); + return; + } + } + + throw new TypeError(`Property ${key} of ${node.type} expected node to be of a type ${JSON.stringify(types)} but instead got ${JSON.stringify(val == null ? void 0 : val.type)}`); + } + + validate.oneOfNodeOrValueTypes = types; + return validate; + } + + function assertValueType(type) { + function validate(node, key, val) { + const valid = getType(val) === type; + + if (!valid) { + throw new TypeError(`Property ${key} expected type of ${type} but got ${getType(val)}`); + } + } + + validate.type = type; + return validate; + } + + function assertShape(shape) { + function validate(node, key, val) { + const errors = []; + + for (const property of Object.keys(shape)) { + try { + (0, validate_1.validateField)(node, property, val[property], shape[property]); + } catch (error) { + if (error instanceof TypeError) { + errors.push(error.message); + continue; + } + + throw error; + } + } + + if (errors.length) { + throw new TypeError(`Property ${key} of ${node.type} expected to have the following:\n${errors.join("\n")}`); + } + } + + validate.shapeOf = shape; + return validate; + } + + function assertOptionalChainStart() { + function validate(node) { + var _current; + + let current = node; + + while (node) { + const { + type + } = current; + + if (type === "OptionalCallExpression") { + if (current.optional) return; + current = current.callee; + continue; + } + + if (type === "OptionalMemberExpression") { + if (current.optional) return; + current = current.object; + continue; + } + + break; + } + + throw new TypeError(`Non-optional ${node.type} must chain from an optional OptionalMemberExpression or OptionalCallExpression. Found chain from ${(_current = current) == null ? void 0 : _current.type}`); + } + + return validate; + } + + function chain(...fns) { + function validate(...args) { + for (const fn of fns) { + fn(...args); + } + } + + validate.chainOf = fns; + return validate; + } + + const validTypeOpts = ["aliases", "builder", "deprecatedAlias", "fields", "inherits", "visitor", "validate"]; + const validFieldKeys = ["default", "optional", "validate"]; + + function defineType(type, opts = {}) { + const inherits = opts.inherits && store[opts.inherits] || {}; + let fields = opts.fields; + + if (!fields) { + fields = {}; + + if (inherits.fields) { + const keys = Object.getOwnPropertyNames(inherits.fields); + + for (const key of keys) { + const field = inherits.fields[key]; + fields[key] = { + default: field.default, + optional: field.optional, + validate: field.validate + }; + } + } + } + + const visitor = opts.visitor || inherits.visitor || []; + const aliases = opts.aliases || inherits.aliases || []; + const builder = opts.builder || inherits.builder || opts.visitor || []; + + for (const k of Object.keys(opts)) { + if (validTypeOpts.indexOf(k) === -1) { + throw new Error(`Unknown type option "${k}" on ${type}`); + } + } + + if (opts.deprecatedAlias) { + DEPRECATED_KEYS[opts.deprecatedAlias] = type; + } + + for (const key of visitor.concat(builder)) { + fields[key] = fields[key] || {}; + } + + for (const key of Object.keys(fields)) { + const field = fields[key]; + + if (field.default !== undefined && builder.indexOf(key) === -1) { + field.optional = true; + } + + if (field.default === undefined) { + field.default = null; + } else if (!field.validate && field.default != null) { + field.validate = assertValueType(getType(field.default)); + } + + for (const k of Object.keys(field)) { + if (validFieldKeys.indexOf(k) === -1) { + throw new Error(`Unknown field key "${k}" on ${type}.${key}`); + } + } + } + + VISITOR_KEYS[type] = opts.visitor = visitor; + BUILDER_KEYS[type] = opts.builder = builder; + NODE_FIELDS[type] = opts.fields = fields; + ALIAS_KEYS[type] = opts.aliases = aliases; + aliases.forEach(alias => { + FLIPPED_ALIAS_KEYS[alias] = FLIPPED_ALIAS_KEYS[alias] || []; + FLIPPED_ALIAS_KEYS[alias].push(type); + }); + + if (opts.validate) { + NODE_PARENT_VALIDATIONS[type] = opts.validate; + } + + store[type] = opts; + } + + const store = {}; + }); + + unwrapExports(utils); + var utils_1 = utils.validate; + var utils_2 = utils.typeIs; + var utils_3 = utils.validateType; + var utils_4 = utils.validateOptional; + var utils_5 = utils.validateOptionalType; + var utils_6 = utils.arrayOf; + var utils_7 = utils.arrayOfType; + var utils_8 = utils.validateArrayOfType; + var utils_9 = utils.assertEach; + var utils_10 = utils.assertOneOf; + var utils_11 = utils.assertNodeType; + var utils_12 = utils.assertNodeOrValueType; + var utils_13 = utils.assertValueType; + var utils_14 = utils.assertShape; + var utils_15 = utils.assertOptionalChainStart; + var utils_16 = utils.chain; + var utils_17 = utils.NODE_PARENT_VALIDATIONS; + var utils_18 = utils.DEPRECATED_KEYS; + var utils_19 = utils.BUILDER_KEYS; + var utils_20 = utils.NODE_FIELDS; + var utils_21 = utils.FLIPPED_ALIAS_KEYS; + var utils_22 = utils.ALIAS_KEYS; + var utils_23 = utils.VISITOR_KEYS; + + var core = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.classMethodOrDeclareMethodCommon = exports.classMethodOrPropertyCommon = exports.patternLikeCommon = exports.functionDeclarationCommon = exports.functionTypeAnnotationCommon = exports.functionCommon = void 0; + + var _is = _interopRequireDefault(is_1); + + var _isValidIdentifier = _interopRequireDefault(isValidIdentifier_1); + + + + + + var _utils = _interopRequireWildcard(utils); + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + (0, _utils.default)("ArrayExpression", { + fields: { + elements: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeOrValueType)("null", "Expression", "SpreadElement"))), + default: !process.env.BABEL_TYPES_8_BREAKING ? [] : undefined + } + }, + visitor: ["elements"], + aliases: ["Expression"] + }); + (0, _utils.default)("AssignmentExpression", { + fields: { + operator: { + validate: function () { + if (!process.env.BABEL_TYPES_8_BREAKING) { + return (0, _utils.assertValueType)("string"); + } + + const identifier = (0, _utils.assertOneOf)(...constants.ASSIGNMENT_OPERATORS); + const pattern = (0, _utils.assertOneOf)("="); + return function (node, key, val) { + const validator = (0, _is.default)("Pattern", node.left) ? pattern : identifier; + validator(node, key, val); + }; + }() + }, + left: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertNodeType)("LVal") : (0, _utils.assertNodeType)("Identifier", "MemberExpression", "ArrayPattern", "ObjectPattern") + }, + right: { + validate: (0, _utils.assertNodeType)("Expression") + } + }, + builder: ["operator", "left", "right"], + visitor: ["left", "right"], + aliases: ["Expression"] + }); + (0, _utils.default)("BinaryExpression", { + builder: ["operator", "left", "right"], + fields: { + operator: { + validate: (0, _utils.assertOneOf)(...constants.BINARY_OPERATORS) + }, + left: { + validate: function () { + const expression = (0, _utils.assertNodeType)("Expression"); + const inOp = (0, _utils.assertNodeType)("Expression", "PrivateName"); + + const validator = function (node, key, val) { + const validator = node.operator === "in" ? inOp : expression; + validator(node, key, val); + }; + + validator.oneOfNodeTypes = ["Expression", "PrivateName"]; + return validator; + }() + }, + right: { + validate: (0, _utils.assertNodeType)("Expression") + } + }, + visitor: ["left", "right"], + aliases: ["Binary", "Expression"] + }); + (0, _utils.default)("InterpreterDirective", { + builder: ["value"], + fields: { + value: { + validate: (0, _utils.assertValueType)("string") + } + } + }); + (0, _utils.default)("Directive", { + visitor: ["value"], + fields: { + value: { + validate: (0, _utils.assertNodeType)("DirectiveLiteral") + } + } + }); + (0, _utils.default)("DirectiveLiteral", { + builder: ["value"], + fields: { + value: { + validate: (0, _utils.assertValueType)("string") + } + } + }); + (0, _utils.default)("BlockStatement", { + builder: ["body", "directives"], + visitor: ["directives", "body"], + fields: { + directives: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Directive"))), + default: [] + }, + body: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Statement"))) + } + }, + aliases: ["Scopable", "BlockParent", "Block", "Statement"] + }); + (0, _utils.default)("BreakStatement", { + visitor: ["label"], + fields: { + label: { + validate: (0, _utils.assertNodeType)("Identifier"), + optional: true + } + }, + aliases: ["Statement", "Terminatorless", "CompletionStatement"] + }); + (0, _utils.default)("CallExpression", { + visitor: ["callee", "arguments", "typeParameters", "typeArguments"], + builder: ["callee", "arguments"], + aliases: ["Expression"], + fields: Object.assign({ + callee: { + validate: (0, _utils.assertNodeType)("Expression", "V8IntrinsicIdentifier") + }, + arguments: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Expression", "SpreadElement", "JSXNamespacedName", "ArgumentPlaceholder"))) + } + }, !process.env.BABEL_TYPES_8_BREAKING ? { + optional: { + validate: (0, _utils.assertOneOf)(true, false), + optional: true + } + } : {}, { + typeArguments: { + validate: (0, _utils.assertNodeType)("TypeParameterInstantiation"), + optional: true + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TSTypeParameterInstantiation"), + optional: true + } + }) + }); + (0, _utils.default)("CatchClause", { + visitor: ["param", "body"], + fields: { + param: { + validate: (0, _utils.assertNodeType)("Identifier", "ArrayPattern", "ObjectPattern"), + optional: true + }, + body: { + validate: (0, _utils.assertNodeType)("BlockStatement") + } + }, + aliases: ["Scopable", "BlockParent"] + }); + (0, _utils.default)("ConditionalExpression", { + visitor: ["test", "consequent", "alternate"], + fields: { + test: { + validate: (0, _utils.assertNodeType)("Expression") + }, + consequent: { + validate: (0, _utils.assertNodeType)("Expression") + }, + alternate: { + validate: (0, _utils.assertNodeType)("Expression") + } + }, + aliases: ["Expression", "Conditional"] + }); + (0, _utils.default)("ContinueStatement", { + visitor: ["label"], + fields: { + label: { + validate: (0, _utils.assertNodeType)("Identifier"), + optional: true + } + }, + aliases: ["Statement", "Terminatorless", "CompletionStatement"] + }); + (0, _utils.default)("DebuggerStatement", { + aliases: ["Statement"] + }); + (0, _utils.default)("DoWhileStatement", { + visitor: ["test", "body"], + fields: { + test: { + validate: (0, _utils.assertNodeType)("Expression") + }, + body: { + validate: (0, _utils.assertNodeType)("Statement") + } + }, + aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"] + }); + (0, _utils.default)("EmptyStatement", { + aliases: ["Statement"] + }); + (0, _utils.default)("ExpressionStatement", { + visitor: ["expression"], + fields: { + expression: { + validate: (0, _utils.assertNodeType)("Expression") + } + }, + aliases: ["Statement", "ExpressionWrapper"] + }); + (0, _utils.default)("File", { + builder: ["program", "comments", "tokens"], + visitor: ["program"], + fields: { + program: { + validate: (0, _utils.assertNodeType)("Program") + }, + comments: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? Object.assign(() => {}, { + each: { + oneOfNodeTypes: ["CommentBlock", "CommentLine"] + } + }) : (0, _utils.assertEach)((0, _utils.assertNodeType)("CommentBlock", "CommentLine")), + optional: true + }, + tokens: { + validate: (0, _utils.assertEach)(Object.assign(() => {}, { + type: "any" + })), + optional: true + } + } + }); + (0, _utils.default)("ForInStatement", { + visitor: ["left", "right", "body"], + aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], + fields: { + left: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertNodeType)("VariableDeclaration", "LVal") : (0, _utils.assertNodeType)("VariableDeclaration", "Identifier", "MemberExpression", "ArrayPattern", "ObjectPattern") + }, + right: { + validate: (0, _utils.assertNodeType)("Expression") + }, + body: { + validate: (0, _utils.assertNodeType)("Statement") + } + } + }); + (0, _utils.default)("ForStatement", { + visitor: ["init", "test", "update", "body"], + aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop"], + fields: { + init: { + validate: (0, _utils.assertNodeType)("VariableDeclaration", "Expression"), + optional: true + }, + test: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + }, + update: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + }, + body: { + validate: (0, _utils.assertNodeType)("Statement") + } + } + }); + const functionCommon = { + params: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Identifier", "Pattern", "RestElement", "TSParameterProperty"))) + }, + generator: { + default: false + }, + async: { + default: false + } + }; + exports.functionCommon = functionCommon; + const functionTypeAnnotationCommon = { + returnType: { + validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"), + optional: true + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TypeParameterDeclaration", "TSTypeParameterDeclaration", "Noop"), + optional: true + } + }; + exports.functionTypeAnnotationCommon = functionTypeAnnotationCommon; + const functionDeclarationCommon = Object.assign({}, functionCommon, { + declare: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + id: { + validate: (0, _utils.assertNodeType)("Identifier"), + optional: true + } + }); + exports.functionDeclarationCommon = functionDeclarationCommon; + (0, _utils.default)("FunctionDeclaration", { + builder: ["id", "params", "body", "generator", "async"], + visitor: ["id", "params", "body", "returnType", "typeParameters"], + fields: Object.assign({}, functionDeclarationCommon, functionTypeAnnotationCommon, { + body: { + validate: (0, _utils.assertNodeType)("BlockStatement") + } + }), + aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Statement", "Pureish", "Declaration"], + validate: function () { + if (!process.env.BABEL_TYPES_8_BREAKING) return () => {}; + const identifier = (0, _utils.assertNodeType)("Identifier"); + return function (parent, key, node) { + if (!(0, _is.default)("ExportDefaultDeclaration", parent)) { + identifier(node, "id", node.id); + } + }; + }() + }); + (0, _utils.default)("FunctionExpression", { + inherits: "FunctionDeclaration", + aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], + fields: Object.assign({}, functionCommon, functionTypeAnnotationCommon, { + id: { + validate: (0, _utils.assertNodeType)("Identifier"), + optional: true + }, + body: { + validate: (0, _utils.assertNodeType)("BlockStatement") + } + }) + }); + const patternLikeCommon = { + typeAnnotation: { + validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"), + optional: true + }, + decorators: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))) + } + }; + exports.patternLikeCommon = patternLikeCommon; + (0, _utils.default)("Identifier", { + builder: ["name"], + visitor: ["typeAnnotation", "decorators"], + aliases: ["Expression", "PatternLike", "LVal", "TSEntityName"], + fields: Object.assign({}, patternLikeCommon, { + name: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), Object.assign(function (node, key, val) { + if (!process.env.BABEL_TYPES_8_BREAKING) return; + + if (!(0, _isValidIdentifier.default)(val, false)) { + throw new TypeError(`"${val}" is not a valid identifier name`); + } + }, { + type: "string" + })) + }, + optional: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + } + }), + + validate(parent, key, node) { + if (!process.env.BABEL_TYPES_8_BREAKING) return; + const match = /\.(\w+)$/.exec(key); + if (!match) return; + const [, parentKey] = match; + const nonComp = { + computed: false + }; + + if (parentKey === "property") { + if ((0, _is.default)("MemberExpression", parent, nonComp)) return; + if ((0, _is.default)("OptionalMemberExpression", parent, nonComp)) return; + } else if (parentKey === "key") { + if ((0, _is.default)("Property", parent, nonComp)) return; + if ((0, _is.default)("Method", parent, nonComp)) return; + } else if (parentKey === "exported") { + if ((0, _is.default)("ExportSpecifier", parent)) return; + } else if (parentKey === "imported") { + if ((0, _is.default)("ImportSpecifier", parent, { + imported: node + })) return; + } else if (parentKey === "meta") { + if ((0, _is.default)("MetaProperty", parent, { + meta: node + })) return; + } + + if (((0, lib.isKeyword)(node.name) || (0, lib.isReservedWord)(node.name)) && node.name !== "this") { + throw new TypeError(`"${node.name}" is not a valid identifier`); + } + } + + }); + (0, _utils.default)("IfStatement", { + visitor: ["test", "consequent", "alternate"], + aliases: ["Statement", "Conditional"], + fields: { + test: { + validate: (0, _utils.assertNodeType)("Expression") + }, + consequent: { + validate: (0, _utils.assertNodeType)("Statement") + }, + alternate: { + optional: true, + validate: (0, _utils.assertNodeType)("Statement") + } + } + }); + (0, _utils.default)("LabeledStatement", { + visitor: ["label", "body"], + aliases: ["Statement"], + fields: { + label: { + validate: (0, _utils.assertNodeType)("Identifier") + }, + body: { + validate: (0, _utils.assertNodeType)("Statement") + } + } + }); + (0, _utils.default)("StringLiteral", { + builder: ["value"], + fields: { + value: { + validate: (0, _utils.assertValueType)("string") + } + }, + aliases: ["Expression", "Pureish", "Literal", "Immutable"] + }); + (0, _utils.default)("NumericLiteral", { + builder: ["value"], + deprecatedAlias: "NumberLiteral", + fields: { + value: { + validate: (0, _utils.assertValueType)("number") + } + }, + aliases: ["Expression", "Pureish", "Literal", "Immutable"] + }); + (0, _utils.default)("NullLiteral", { + aliases: ["Expression", "Pureish", "Literal", "Immutable"] + }); + (0, _utils.default)("BooleanLiteral", { + builder: ["value"], + fields: { + value: { + validate: (0, _utils.assertValueType)("boolean") + } + }, + aliases: ["Expression", "Pureish", "Literal", "Immutable"] + }); + (0, _utils.default)("RegExpLiteral", { + builder: ["pattern", "flags"], + deprecatedAlias: "RegexLiteral", + aliases: ["Expression", "Pureish", "Literal"], + fields: { + pattern: { + validate: (0, _utils.assertValueType)("string") + }, + flags: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), Object.assign(function (node, key, val) { + if (!process.env.BABEL_TYPES_8_BREAKING) return; + const invalid = /[^gimsuy]/.exec(val); + + if (invalid) { + throw new TypeError(`"${invalid[0]}" is not a valid RegExp flag`); + } + }, { + type: "string" + })), + default: "" + } + } + }); + (0, _utils.default)("LogicalExpression", { + builder: ["operator", "left", "right"], + visitor: ["left", "right"], + aliases: ["Binary", "Expression"], + fields: { + operator: { + validate: (0, _utils.assertOneOf)(...constants.LOGICAL_OPERATORS) + }, + left: { + validate: (0, _utils.assertNodeType)("Expression") + }, + right: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + (0, _utils.default)("MemberExpression", { + builder: ["object", "property", "computed", "optional"], + visitor: ["object", "property"], + aliases: ["Expression", "LVal"], + fields: Object.assign({ + object: { + validate: (0, _utils.assertNodeType)("Expression") + }, + property: { + validate: function () { + const normal = (0, _utils.assertNodeType)("Identifier", "PrivateName"); + const computed = (0, _utils.assertNodeType)("Expression"); + + const validator = function (node, key, val) { + const validator = node.computed ? computed : normal; + validator(node, key, val); + }; + + validator.oneOfNodeTypes = ["Expression", "Identifier", "PrivateName"]; + return validator; + }() + }, + computed: { + default: false + } + }, !process.env.BABEL_TYPES_8_BREAKING ? { + optional: { + validate: (0, _utils.assertOneOf)(true, false), + optional: true + } + } : {}) + }); + (0, _utils.default)("NewExpression", { + inherits: "CallExpression" + }); + (0, _utils.default)("Program", { + visitor: ["directives", "body"], + builder: ["body", "directives", "sourceType", "interpreter"], + fields: { + sourceFile: { + validate: (0, _utils.assertValueType)("string") + }, + sourceType: { + validate: (0, _utils.assertOneOf)("script", "module"), + default: "script" + }, + interpreter: { + validate: (0, _utils.assertNodeType)("InterpreterDirective"), + default: null, + optional: true + }, + directives: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Directive"))), + default: [] + }, + body: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Statement"))) + } + }, + aliases: ["Scopable", "BlockParent", "Block"] + }); + (0, _utils.default)("ObjectExpression", { + visitor: ["properties"], + aliases: ["Expression"], + fields: { + properties: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("ObjectMethod", "ObjectProperty", "SpreadElement"))) + } + } + }); + (0, _utils.default)("ObjectMethod", { + builder: ["kind", "key", "params", "body", "computed", "generator", "async"], + fields: Object.assign({}, functionCommon, functionTypeAnnotationCommon, { + kind: Object.assign({ + validate: (0, _utils.assertOneOf)("method", "get", "set") + }, !process.env.BABEL_TYPES_8_BREAKING ? { + default: "method" + } : {}), + computed: { + default: false + }, + key: { + validate: function () { + const normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral"); + const computed = (0, _utils.assertNodeType)("Expression"); + + const validator = function (node, key, val) { + const validator = node.computed ? computed : normal; + validator(node, key, val); + }; + + validator.oneOfNodeTypes = ["Expression", "Identifier", "StringLiteral", "NumericLiteral"]; + return validator; + }() + }, + decorators: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), + optional: true + }, + body: { + validate: (0, _utils.assertNodeType)("BlockStatement") + } + }), + visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], + aliases: ["UserWhitespacable", "Function", "Scopable", "BlockParent", "FunctionParent", "Method", "ObjectMember"] + }); + (0, _utils.default)("ObjectProperty", { + builder: ["key", "value", "computed", "shorthand", ...(!process.env.BABEL_TYPES_8_BREAKING ? ["decorators"] : [])], + fields: { + computed: { + default: false + }, + key: { + validate: function () { + const normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral"); + const computed = (0, _utils.assertNodeType)("Expression"); + + const validator = function (node, key, val) { + const validator = node.computed ? computed : normal; + validator(node, key, val); + }; + + validator.oneOfNodeTypes = ["Expression", "Identifier", "StringLiteral", "NumericLiteral"]; + return validator; + }() + }, + value: { + validate: (0, _utils.assertNodeType)("Expression", "PatternLike") + }, + shorthand: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("boolean"), Object.assign(function (node, key, val) { + if (!process.env.BABEL_TYPES_8_BREAKING) return; + + if (val && node.computed) { + throw new TypeError("Property shorthand of ObjectProperty cannot be true if computed is true"); + } + }, { + type: "boolean" + }), function (node, key, val) { + if (!process.env.BABEL_TYPES_8_BREAKING) return; + + if (val && !(0, _is.default)("Identifier", node.key)) { + throw new TypeError("Property shorthand of ObjectProperty cannot be true if key is not an Identifier"); + } + }), + default: false + }, + decorators: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), + optional: true + } + }, + visitor: ["key", "value", "decorators"], + aliases: ["UserWhitespacable", "Property", "ObjectMember"], + validate: function () { + const pattern = (0, _utils.assertNodeType)("Identifier", "Pattern"); + const expression = (0, _utils.assertNodeType)("Expression"); + return function (parent, key, node) { + if (!process.env.BABEL_TYPES_8_BREAKING) return; + const validator = (0, _is.default)("ObjectPattern", parent) ? pattern : expression; + validator(node, "value", node.value); + }; + }() + }); + (0, _utils.default)("RestElement", { + visitor: ["argument", "typeAnnotation"], + builder: ["argument"], + aliases: ["LVal", "PatternLike"], + deprecatedAlias: "RestProperty", + fields: Object.assign({}, patternLikeCommon, { + argument: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertNodeType)("LVal") : (0, _utils.assertNodeType)("Identifier", "Pattern", "MemberExpression") + } + }), + + validate(parent, key) { + if (!process.env.BABEL_TYPES_8_BREAKING) return; + const match = /(\w+)\[(\d+)\]/.exec(key); + if (!match) throw new Error("Internal Babel error: malformed key."); + const [, listKey, index] = match; + + if (parent[listKey].length > index + 1) { + throw new TypeError(`RestElement must be last element of ${listKey}`); + } + } + + }); + (0, _utils.default)("ReturnStatement", { + visitor: ["argument"], + aliases: ["Statement", "Terminatorless", "CompletionStatement"], + fields: { + argument: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + } + } + }); + (0, _utils.default)("SequenceExpression", { + visitor: ["expressions"], + fields: { + expressions: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Expression"))) + } + }, + aliases: ["Expression"] + }); + (0, _utils.default)("ParenthesizedExpression", { + visitor: ["expression"], + aliases: ["Expression", "ExpressionWrapper"], + fields: { + expression: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + (0, _utils.default)("SwitchCase", { + visitor: ["test", "consequent"], + fields: { + test: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + }, + consequent: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Statement"))) + } + } + }); + (0, _utils.default)("SwitchStatement", { + visitor: ["discriminant", "cases"], + aliases: ["Statement", "BlockParent", "Scopable"], + fields: { + discriminant: { + validate: (0, _utils.assertNodeType)("Expression") + }, + cases: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("SwitchCase"))) + } + } + }); + (0, _utils.default)("ThisExpression", { + aliases: ["Expression"] + }); + (0, _utils.default)("ThrowStatement", { + visitor: ["argument"], + aliases: ["Statement", "Terminatorless", "CompletionStatement"], + fields: { + argument: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + (0, _utils.default)("TryStatement", { + visitor: ["block", "handler", "finalizer"], + aliases: ["Statement"], + fields: { + block: { + validate: (0, _utils.chain)((0, _utils.assertNodeType)("BlockStatement"), Object.assign(function (node) { + if (!process.env.BABEL_TYPES_8_BREAKING) return; + + if (!node.handler && !node.finalizer) { + throw new TypeError("TryStatement expects either a handler or finalizer, or both"); + } + }, { + oneOfNodeTypes: ["BlockStatement"] + })) + }, + handler: { + optional: true, + validate: (0, _utils.assertNodeType)("CatchClause") + }, + finalizer: { + optional: true, + validate: (0, _utils.assertNodeType)("BlockStatement") + } + } + }); + (0, _utils.default)("UnaryExpression", { + builder: ["operator", "argument", "prefix"], + fields: { + prefix: { + default: true + }, + argument: { + validate: (0, _utils.assertNodeType)("Expression") + }, + operator: { + validate: (0, _utils.assertOneOf)(...constants.UNARY_OPERATORS) + } + }, + visitor: ["argument"], + aliases: ["UnaryLike", "Expression"] + }); + (0, _utils.default)("UpdateExpression", { + builder: ["operator", "argument", "prefix"], + fields: { + prefix: { + default: false + }, + argument: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertNodeType)("Expression") : (0, _utils.assertNodeType)("Identifier", "MemberExpression") + }, + operator: { + validate: (0, _utils.assertOneOf)(...constants.UPDATE_OPERATORS) + } + }, + visitor: ["argument"], + aliases: ["Expression"] + }); + (0, _utils.default)("VariableDeclaration", { + builder: ["kind", "declarations"], + visitor: ["declarations"], + aliases: ["Statement", "Declaration"], + fields: { + declare: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + kind: { + validate: (0, _utils.assertOneOf)("var", "let", "const") + }, + declarations: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("VariableDeclarator"))) + } + }, + + validate(parent, key, node) { + if (!process.env.BABEL_TYPES_8_BREAKING) return; + if (!(0, _is.default)("ForXStatement", parent, { + left: node + })) return; + + if (node.declarations.length !== 1) { + throw new TypeError(`Exactly one VariableDeclarator is required in the VariableDeclaration of a ${parent.type}`); + } + } + + }); + (0, _utils.default)("VariableDeclarator", { + visitor: ["id", "init"], + fields: { + id: { + validate: function () { + if (!process.env.BABEL_TYPES_8_BREAKING) { + return (0, _utils.assertNodeType)("LVal"); + } + + const normal = (0, _utils.assertNodeType)("Identifier", "ArrayPattern", "ObjectPattern"); + const without = (0, _utils.assertNodeType)("Identifier"); + return function (node, key, val) { + const validator = node.init ? normal : without; + validator(node, key, val); + }; + }() + }, + definite: { + optional: true, + validate: (0, _utils.assertValueType)("boolean") + }, + init: { + optional: true, + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + (0, _utils.default)("WhileStatement", { + visitor: ["test", "body"], + aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"], + fields: { + test: { + validate: (0, _utils.assertNodeType)("Expression") + }, + body: { + validate: (0, _utils.assertNodeType)("Statement") + } + } + }); + (0, _utils.default)("WithStatement", { + visitor: ["object", "body"], + aliases: ["Statement"], + fields: { + object: { + validate: (0, _utils.assertNodeType)("Expression") + }, + body: { + validate: (0, _utils.assertNodeType)("Statement") + } + } + }); + (0, _utils.default)("AssignmentPattern", { + visitor: ["left", "right", "decorators"], + builder: ["left", "right"], + aliases: ["Pattern", "PatternLike", "LVal"], + fields: Object.assign({}, patternLikeCommon, { + left: { + validate: (0, _utils.assertNodeType)("Identifier", "ObjectPattern", "ArrayPattern", "MemberExpression") + }, + right: { + validate: (0, _utils.assertNodeType)("Expression") + }, + decorators: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), + optional: true + } + }) + }); + (0, _utils.default)("ArrayPattern", { + visitor: ["elements", "typeAnnotation"], + builder: ["elements"], + aliases: ["Pattern", "PatternLike", "LVal"], + fields: Object.assign({}, patternLikeCommon, { + elements: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeOrValueType)("null", "PatternLike"))) + }, + decorators: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), + optional: true + } + }) + }); + (0, _utils.default)("ArrowFunctionExpression", { + builder: ["params", "body", "async"], + visitor: ["params", "body", "returnType", "typeParameters"], + aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], + fields: Object.assign({}, functionCommon, functionTypeAnnotationCommon, { + expression: { + validate: (0, _utils.assertValueType)("boolean") + }, + body: { + validate: (0, _utils.assertNodeType)("BlockStatement", "Expression") + } + }) + }); + (0, _utils.default)("ClassBody", { + visitor: ["body"], + fields: { + body: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("ClassMethod", "ClassPrivateMethod", "ClassProperty", "ClassPrivateProperty", "TSDeclareMethod", "TSIndexSignature"))) + } + } + }); + (0, _utils.default)("ClassExpression", { + builder: ["id", "superClass", "body", "decorators"], + visitor: ["id", "body", "superClass", "mixins", "typeParameters", "superTypeParameters", "implements", "decorators"], + aliases: ["Scopable", "Class", "Expression"], + fields: { + id: { + validate: (0, _utils.assertNodeType)("Identifier"), + optional: true + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TypeParameterDeclaration", "TSTypeParameterDeclaration", "Noop"), + optional: true + }, + body: { + validate: (0, _utils.assertNodeType)("ClassBody") + }, + superClass: { + optional: true, + validate: (0, _utils.assertNodeType)("Expression") + }, + superTypeParameters: { + validate: (0, _utils.assertNodeType)("TypeParameterInstantiation", "TSTypeParameterInstantiation"), + optional: true + }, + implements: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("TSExpressionWithTypeArguments", "ClassImplements"))), + optional: true + }, + decorators: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), + optional: true + }, + mixins: { + validate: (0, _utils.assertNodeType)("InterfaceExtends"), + optional: true + } + } + }); + (0, _utils.default)("ClassDeclaration", { + inherits: "ClassExpression", + aliases: ["Scopable", "Class", "Statement", "Declaration"], + fields: { + id: { + validate: (0, _utils.assertNodeType)("Identifier") + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TypeParameterDeclaration", "TSTypeParameterDeclaration", "Noop"), + optional: true + }, + body: { + validate: (0, _utils.assertNodeType)("ClassBody") + }, + superClass: { + optional: true, + validate: (0, _utils.assertNodeType)("Expression") + }, + superTypeParameters: { + validate: (0, _utils.assertNodeType)("TypeParameterInstantiation", "TSTypeParameterInstantiation"), + optional: true + }, + implements: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("TSExpressionWithTypeArguments", "ClassImplements"))), + optional: true + }, + decorators: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), + optional: true + }, + mixins: { + validate: (0, _utils.assertNodeType)("InterfaceExtends"), + optional: true + }, + declare: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + abstract: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + } + }, + validate: function () { + const identifier = (0, _utils.assertNodeType)("Identifier"); + return function (parent, key, node) { + if (!process.env.BABEL_TYPES_8_BREAKING) return; + + if (!(0, _is.default)("ExportDefaultDeclaration", parent)) { + identifier(node, "id", node.id); + } + }; + }() + }); + (0, _utils.default)("ExportAllDeclaration", { + visitor: ["source"], + aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], + fields: { + source: { + validate: (0, _utils.assertNodeType)("StringLiteral") + }, + assertions: { + optional: true, + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertNodeType)("ImportAttribute")) + } + } + }); + (0, _utils.default)("ExportDefaultDeclaration", { + visitor: ["declaration"], + aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], + fields: { + declaration: { + validate: (0, _utils.assertNodeType)("FunctionDeclaration", "TSDeclareFunction", "ClassDeclaration", "Expression") + } + } + }); + (0, _utils.default)("ExportNamedDeclaration", { + visitor: ["declaration", "specifiers", "source"], + aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], + fields: { + declaration: { + optional: true, + validate: (0, _utils.chain)((0, _utils.assertNodeType)("Declaration"), Object.assign(function (node, key, val) { + if (!process.env.BABEL_TYPES_8_BREAKING) return; + + if (val && node.specifiers.length) { + throw new TypeError("Only declaration or specifiers is allowed on ExportNamedDeclaration"); + } + }, { + oneOfNodeTypes: ["Declaration"] + }), function (node, key, val) { + if (!process.env.BABEL_TYPES_8_BREAKING) return; + + if (val && node.source) { + throw new TypeError("Cannot export a declaration from a source"); + } + }) + }, + assertions: { + optional: true, + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertNodeType)("ImportAttribute")) + }, + specifiers: { + default: [], + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)(function () { + const sourced = (0, _utils.assertNodeType)("ExportSpecifier", "ExportDefaultSpecifier", "ExportNamespaceSpecifier"); + const sourceless = (0, _utils.assertNodeType)("ExportSpecifier"); + if (!process.env.BABEL_TYPES_8_BREAKING) return sourced; + return function (node, key, val) { + const validator = node.source ? sourced : sourceless; + validator(node, key, val); + }; + }())) + }, + source: { + validate: (0, _utils.assertNodeType)("StringLiteral"), + optional: true + }, + exportKind: (0, _utils.validateOptional)((0, _utils.assertOneOf)("type", "value")) + } + }); + (0, _utils.default)("ExportSpecifier", { + visitor: ["local", "exported"], + aliases: ["ModuleSpecifier"], + fields: { + local: { + validate: (0, _utils.assertNodeType)("Identifier") + }, + exported: { + validate: (0, _utils.assertNodeType)("Identifier", "StringLiteral") + } + } + }); + (0, _utils.default)("ForOfStatement", { + visitor: ["left", "right", "body"], + builder: ["left", "right", "body", "await"], + aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], + fields: { + left: { + validate: function () { + if (!process.env.BABEL_TYPES_8_BREAKING) { + return (0, _utils.assertNodeType)("VariableDeclaration", "LVal"); + } + + const declaration = (0, _utils.assertNodeType)("VariableDeclaration"); + const lval = (0, _utils.assertNodeType)("Identifier", "MemberExpression", "ArrayPattern", "ObjectPattern"); + return function (node, key, val) { + if ((0, _is.default)("VariableDeclaration", val)) { + declaration(node, key, val); + } else { + lval(node, key, val); + } + }; + }() + }, + right: { + validate: (0, _utils.assertNodeType)("Expression") + }, + body: { + validate: (0, _utils.assertNodeType)("Statement") + }, + await: { + default: false + } + } + }); + (0, _utils.default)("ImportDeclaration", { + visitor: ["specifiers", "source"], + aliases: ["Statement", "Declaration", "ModuleDeclaration"], + fields: { + assertions: { + optional: true, + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertNodeType)("ImportAttribute")) + }, + specifiers: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("ImportSpecifier", "ImportDefaultSpecifier", "ImportNamespaceSpecifier"))) + }, + source: { + validate: (0, _utils.assertNodeType)("StringLiteral") + }, + importKind: { + validate: (0, _utils.assertOneOf)("type", "typeof", "value"), + optional: true + } + } + }); + (0, _utils.default)("ImportDefaultSpecifier", { + visitor: ["local"], + aliases: ["ModuleSpecifier"], + fields: { + local: { + validate: (0, _utils.assertNodeType)("Identifier") + } + } + }); + (0, _utils.default)("ImportNamespaceSpecifier", { + visitor: ["local"], + aliases: ["ModuleSpecifier"], + fields: { + local: { + validate: (0, _utils.assertNodeType)("Identifier") + } + } + }); + (0, _utils.default)("ImportSpecifier", { + visitor: ["local", "imported"], + aliases: ["ModuleSpecifier"], + fields: { + local: { + validate: (0, _utils.assertNodeType)("Identifier") + }, + imported: { + validate: (0, _utils.assertNodeType)("Identifier", "StringLiteral") + }, + importKind: { + validate: (0, _utils.assertOneOf)("type", "typeof"), + optional: true + } + } + }); + (0, _utils.default)("MetaProperty", { + visitor: ["meta", "property"], + aliases: ["Expression"], + fields: { + meta: { + validate: (0, _utils.chain)((0, _utils.assertNodeType)("Identifier"), Object.assign(function (node, key, val) { + if (!process.env.BABEL_TYPES_8_BREAKING) return; + let property; + + switch (val.name) { + case "function": + property = "sent"; + break; + + case "new": + property = "target"; + break; + + case "import": + property = "meta"; + break; + } + + if (!(0, _is.default)("Identifier", node.property, { + name: property + })) { + throw new TypeError("Unrecognised MetaProperty"); + } + }, { + oneOfNodeTypes: ["Identifier"] + })) + }, + property: { + validate: (0, _utils.assertNodeType)("Identifier") + } + } + }); + const classMethodOrPropertyCommon = { + abstract: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + accessibility: { + validate: (0, _utils.assertOneOf)("public", "private", "protected"), + optional: true + }, + static: { + default: false + }, + computed: { + default: false + }, + optional: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + key: { + validate: (0, _utils.chain)(function () { + const normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral"); + const computed = (0, _utils.assertNodeType)("Expression"); + return function (node, key, val) { + const validator = node.computed ? computed : normal; + validator(node, key, val); + }; + }(), (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral", "Expression")) + } + }; + exports.classMethodOrPropertyCommon = classMethodOrPropertyCommon; + const classMethodOrDeclareMethodCommon = Object.assign({}, functionCommon, classMethodOrPropertyCommon, { + kind: { + validate: (0, _utils.assertOneOf)("get", "set", "method", "constructor"), + default: "method" + }, + access: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), (0, _utils.assertOneOf)("public", "private", "protected")), + optional: true + }, + decorators: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), + optional: true + } + }); + exports.classMethodOrDeclareMethodCommon = classMethodOrDeclareMethodCommon; + (0, _utils.default)("ClassMethod", { + aliases: ["Function", "Scopable", "BlockParent", "FunctionParent", "Method"], + builder: ["kind", "key", "params", "body", "computed", "static", "generator", "async"], + visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], + fields: Object.assign({}, classMethodOrDeclareMethodCommon, functionTypeAnnotationCommon, { + body: { + validate: (0, _utils.assertNodeType)("BlockStatement") + } + }) + }); + (0, _utils.default)("ObjectPattern", { + visitor: ["properties", "typeAnnotation", "decorators"], + builder: ["properties"], + aliases: ["Pattern", "PatternLike", "LVal"], + fields: Object.assign({}, patternLikeCommon, { + properties: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("RestElement", "ObjectProperty"))) + } + }) + }); + (0, _utils.default)("SpreadElement", { + visitor: ["argument"], + aliases: ["UnaryLike"], + deprecatedAlias: "SpreadProperty", + fields: { + argument: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + (0, _utils.default)("Super", { + aliases: ["Expression"] + }); + (0, _utils.default)("TaggedTemplateExpression", { + visitor: ["tag", "quasi"], + aliases: ["Expression"], + fields: { + tag: { + validate: (0, _utils.assertNodeType)("Expression") + }, + quasi: { + validate: (0, _utils.assertNodeType)("TemplateLiteral") + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TypeParameterInstantiation", "TSTypeParameterInstantiation"), + optional: true + } + } + }); + (0, _utils.default)("TemplateElement", { + builder: ["value", "tail"], + fields: { + value: { + validate: (0, _utils.assertShape)({ + raw: { + validate: (0, _utils.assertValueType)("string") + }, + cooked: { + validate: (0, _utils.assertValueType)("string"), + optional: true + } + }) + }, + tail: { + default: false + } + } + }); + (0, _utils.default)("TemplateLiteral", { + visitor: ["quasis", "expressions"], + aliases: ["Expression", "Literal"], + fields: { + quasis: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("TemplateElement"))) + }, + expressions: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Expression", "TSType")), function (node, key, val) { + if (node.quasis.length !== val.length + 1) { + throw new TypeError(`Number of ${node.type} quasis should be exactly one more than the number of expressions.\nExpected ${val.length + 1} quasis but got ${node.quasis.length}`); + } + }) + } + } + }); + (0, _utils.default)("YieldExpression", { + builder: ["argument", "delegate"], + visitor: ["argument"], + aliases: ["Expression", "Terminatorless"], + fields: { + delegate: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("boolean"), Object.assign(function (node, key, val) { + if (!process.env.BABEL_TYPES_8_BREAKING) return; + + if (val && !node.argument) { + throw new TypeError("Property delegate of YieldExpression cannot be true if there is no argument"); + } + }, { + type: "boolean" + })), + default: false + }, + argument: { + optional: true, + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + (0, _utils.default)("AwaitExpression", { + builder: ["argument"], + visitor: ["argument"], + aliases: ["Expression", "Terminatorless"], + fields: { + argument: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + (0, _utils.default)("Import", { + aliases: ["Expression"] + }); + (0, _utils.default)("BigIntLiteral", { + builder: ["value"], + fields: { + value: { + validate: (0, _utils.assertValueType)("string") + } + }, + aliases: ["Expression", "Pureish", "Literal", "Immutable"] + }); + (0, _utils.default)("ExportNamespaceSpecifier", { + visitor: ["exported"], + aliases: ["ModuleSpecifier"], + fields: { + exported: { + validate: (0, _utils.assertNodeType)("Identifier") + } + } + }); + (0, _utils.default)("OptionalMemberExpression", { + builder: ["object", "property", "computed", "optional"], + visitor: ["object", "property"], + aliases: ["Expression"], + fields: { + object: { + validate: (0, _utils.assertNodeType)("Expression") + }, + property: { + validate: function () { + const normal = (0, _utils.assertNodeType)("Identifier"); + const computed = (0, _utils.assertNodeType)("Expression"); + + const validator = function (node, key, val) { + const validator = node.computed ? computed : normal; + validator(node, key, val); + }; + + validator.oneOfNodeTypes = ["Expression", "Identifier"]; + return validator; + }() + }, + computed: { + default: false + }, + optional: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertValueType)("boolean") : (0, _utils.chain)((0, _utils.assertValueType)("boolean"), (0, _utils.assertOptionalChainStart)()) + } + } + }); + (0, _utils.default)("OptionalCallExpression", { + visitor: ["callee", "arguments", "typeParameters", "typeArguments"], + builder: ["callee", "arguments", "optional"], + aliases: ["Expression"], + fields: { + callee: { + validate: (0, _utils.assertNodeType)("Expression") + }, + arguments: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Expression", "SpreadElement", "JSXNamespacedName"))) + }, + optional: { + validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertValueType)("boolean") : (0, _utils.chain)((0, _utils.assertValueType)("boolean"), (0, _utils.assertOptionalChainStart)()) + }, + typeArguments: { + validate: (0, _utils.assertNodeType)("TypeParameterInstantiation"), + optional: true + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TSTypeParameterInstantiation"), + optional: true + } + } + }); + }); + + unwrapExports(core); + var core_1 = core.classMethodOrDeclareMethodCommon; + var core_2 = core.classMethodOrPropertyCommon; + var core_3 = core.patternLikeCommon; + var core_4 = core.functionDeclarationCommon; + var core_5 = core.functionTypeAnnotationCommon; + var core_6 = core.functionCommon; + + var flow = createCommonjsModule(function (module) { + + var _utils = _interopRequireWildcard(utils); + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + const defineInterfaceishType = (name, typeParameterType = "TypeParameterDeclaration") => { + (0, _utils.default)(name, { + builder: ["id", "typeParameters", "extends", "body"], + visitor: ["id", "typeParameters", "extends", "mixins", "implements", "body"], + aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)(typeParameterType), + extends: (0, _utils.validateOptional)((0, _utils.arrayOfType)("InterfaceExtends")), + mixins: (0, _utils.validateOptional)((0, _utils.arrayOfType)("InterfaceExtends")), + implements: (0, _utils.validateOptional)((0, _utils.arrayOfType)("ClassImplements")), + body: (0, _utils.validateType)("ObjectTypeAnnotation") + } + }); + }; + + (0, _utils.default)("AnyTypeAnnotation", { + aliases: ["Flow", "FlowType", "FlowBaseAnnotation"] + }); + (0, _utils.default)("ArrayTypeAnnotation", { + visitor: ["elementType"], + aliases: ["Flow", "FlowType"], + fields: { + elementType: (0, _utils.validateType)("FlowType") + } + }); + (0, _utils.default)("BooleanTypeAnnotation", { + aliases: ["Flow", "FlowType", "FlowBaseAnnotation"] + }); + (0, _utils.default)("BooleanLiteralTypeAnnotation", { + builder: ["value"], + aliases: ["Flow", "FlowType"], + fields: { + value: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) + } + }); + (0, _utils.default)("NullLiteralTypeAnnotation", { + aliases: ["Flow", "FlowType", "FlowBaseAnnotation"] + }); + (0, _utils.default)("ClassImplements", { + visitor: ["id", "typeParameters"], + aliases: ["Flow"], + fields: { + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterInstantiation") + } + }); + defineInterfaceishType("DeclareClass"); + (0, _utils.default)("DeclareFunction", { + visitor: ["id"], + aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)("Identifier"), + predicate: (0, _utils.validateOptionalType)("DeclaredPredicate") + } + }); + defineInterfaceishType("DeclareInterface"); + (0, _utils.default)("DeclareModule", { + builder: ["id", "body", "kind"], + visitor: ["id", "body"], + aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)(["Identifier", "StringLiteral"]), + body: (0, _utils.validateType)("BlockStatement"), + kind: (0, _utils.validateOptional)((0, _utils.assertOneOf)("CommonJS", "ES")) + } + }); + (0, _utils.default)("DeclareModuleExports", { + visitor: ["typeAnnotation"], + aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], + fields: { + typeAnnotation: (0, _utils.validateType)("TypeAnnotation") + } + }); + (0, _utils.default)("DeclareTypeAlias", { + visitor: ["id", "typeParameters", "right"], + aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), + right: (0, _utils.validateType)("FlowType") + } + }); + (0, _utils.default)("DeclareOpaqueType", { + visitor: ["id", "typeParameters", "supertype"], + aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), + supertype: (0, _utils.validateOptionalType)("FlowType") + } + }); + (0, _utils.default)("DeclareVariable", { + visitor: ["id"], + aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)("Identifier") + } + }); + (0, _utils.default)("DeclareExportDeclaration", { + visitor: ["declaration", "specifiers", "source"], + aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], + fields: { + declaration: (0, _utils.validateOptionalType)("Flow"), + specifiers: (0, _utils.validateOptional)((0, _utils.arrayOfType)(["ExportSpecifier", "ExportNamespaceSpecifier"])), + source: (0, _utils.validateOptionalType)("StringLiteral"), + default: (0, _utils.validateOptional)((0, _utils.assertValueType)("boolean")) + } + }); + (0, _utils.default)("DeclareExportAllDeclaration", { + visitor: ["source"], + aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], + fields: { + source: (0, _utils.validateType)("StringLiteral"), + exportKind: (0, _utils.validateOptional)((0, _utils.assertOneOf)("type", "value")) + } + }); + (0, _utils.default)("DeclaredPredicate", { + visitor: ["value"], + aliases: ["Flow", "FlowPredicate"], + fields: { + value: (0, _utils.validateType)("Flow") + } + }); + (0, _utils.default)("ExistsTypeAnnotation", { + aliases: ["Flow", "FlowType"] + }); + (0, _utils.default)("FunctionTypeAnnotation", { + visitor: ["typeParameters", "params", "rest", "returnType"], + aliases: ["Flow", "FlowType"], + fields: { + typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), + params: (0, _utils.validate)((0, _utils.arrayOfType)("FunctionTypeParam")), + rest: (0, _utils.validateOptionalType)("FunctionTypeParam"), + returnType: (0, _utils.validateType)("FlowType") + } + }); + (0, _utils.default)("FunctionTypeParam", { + visitor: ["name", "typeAnnotation"], + aliases: ["Flow"], + fields: { + name: (0, _utils.validateOptionalType)("Identifier"), + typeAnnotation: (0, _utils.validateType)("FlowType"), + optional: (0, _utils.validateOptional)((0, _utils.assertValueType)("boolean")) + } + }); + (0, _utils.default)("GenericTypeAnnotation", { + visitor: ["id", "typeParameters"], + aliases: ["Flow", "FlowType"], + fields: { + id: (0, _utils.validateType)(["Identifier", "QualifiedTypeIdentifier"]), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterInstantiation") + } + }); + (0, _utils.default)("InferredPredicate", { + aliases: ["Flow", "FlowPredicate"] + }); + (0, _utils.default)("InterfaceExtends", { + visitor: ["id", "typeParameters"], + aliases: ["Flow"], + fields: { + id: (0, _utils.validateType)(["Identifier", "QualifiedTypeIdentifier"]), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterInstantiation") + } + }); + defineInterfaceishType("InterfaceDeclaration"); + (0, _utils.default)("InterfaceTypeAnnotation", { + visitor: ["extends", "body"], + aliases: ["Flow", "FlowType"], + fields: { + extends: (0, _utils.validateOptional)((0, _utils.arrayOfType)("InterfaceExtends")), + body: (0, _utils.validateType)("ObjectTypeAnnotation") + } + }); + (0, _utils.default)("IntersectionTypeAnnotation", { + visitor: ["types"], + aliases: ["Flow", "FlowType"], + fields: { + types: (0, _utils.validate)((0, _utils.arrayOfType)("FlowType")) + } + }); + (0, _utils.default)("MixedTypeAnnotation", { + aliases: ["Flow", "FlowType", "FlowBaseAnnotation"] + }); + (0, _utils.default)("EmptyTypeAnnotation", { + aliases: ["Flow", "FlowType", "FlowBaseAnnotation"] + }); + (0, _utils.default)("NullableTypeAnnotation", { + visitor: ["typeAnnotation"], + aliases: ["Flow", "FlowType"], + fields: { + typeAnnotation: (0, _utils.validateType)("FlowType") + } + }); + (0, _utils.default)("NumberLiteralTypeAnnotation", { + builder: ["value"], + aliases: ["Flow", "FlowType"], + fields: { + value: (0, _utils.validate)((0, _utils.assertValueType)("number")) + } + }); + (0, _utils.default)("NumberTypeAnnotation", { + aliases: ["Flow", "FlowType", "FlowBaseAnnotation"] + }); + (0, _utils.default)("ObjectTypeAnnotation", { + visitor: ["properties", "indexers", "callProperties", "internalSlots"], + aliases: ["Flow", "FlowType"], + builder: ["properties", "indexers", "callProperties", "internalSlots", "exact"], + fields: { + properties: (0, _utils.validate)((0, _utils.arrayOfType)(["ObjectTypeProperty", "ObjectTypeSpreadProperty"])), + indexers: (0, _utils.validateOptional)((0, _utils.arrayOfType)("ObjectTypeIndexer")), + callProperties: (0, _utils.validateOptional)((0, _utils.arrayOfType)("ObjectTypeCallProperty")), + internalSlots: (0, _utils.validateOptional)((0, _utils.arrayOfType)("ObjectTypeInternalSlot")), + exact: { + validate: (0, _utils.assertValueType)("boolean"), + default: false + }, + inexact: (0, _utils.validateOptional)((0, _utils.assertValueType)("boolean")) + } + }); + (0, _utils.default)("ObjectTypeInternalSlot", { + visitor: ["id", "value", "optional", "static", "method"], + aliases: ["Flow", "UserWhitespacable"], + fields: { + id: (0, _utils.validateType)("Identifier"), + value: (0, _utils.validateType)("FlowType"), + optional: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + static: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + method: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) + } + }); + (0, _utils.default)("ObjectTypeCallProperty", { + visitor: ["value"], + aliases: ["Flow", "UserWhitespacable"], + fields: { + value: (0, _utils.validateType)("FlowType"), + static: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) + } + }); + (0, _utils.default)("ObjectTypeIndexer", { + visitor: ["id", "key", "value", "variance"], + aliases: ["Flow", "UserWhitespacable"], + fields: { + id: (0, _utils.validateOptionalType)("Identifier"), + key: (0, _utils.validateType)("FlowType"), + value: (0, _utils.validateType)("FlowType"), + static: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + variance: (0, _utils.validateOptionalType)("Variance") + } + }); + (0, _utils.default)("ObjectTypeProperty", { + visitor: ["key", "value", "variance"], + aliases: ["Flow", "UserWhitespacable"], + fields: { + key: (0, _utils.validateType)(["Identifier", "StringLiteral"]), + value: (0, _utils.validateType)("FlowType"), + kind: (0, _utils.validate)((0, _utils.assertOneOf)("init", "get", "set")), + static: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + proto: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + optional: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + variance: (0, _utils.validateOptionalType)("Variance") + } + }); + (0, _utils.default)("ObjectTypeSpreadProperty", { + visitor: ["argument"], + aliases: ["Flow", "UserWhitespacable"], + fields: { + argument: (0, _utils.validateType)("FlowType") + } + }); + (0, _utils.default)("OpaqueType", { + visitor: ["id", "typeParameters", "supertype", "impltype"], + aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), + supertype: (0, _utils.validateOptionalType)("FlowType"), + impltype: (0, _utils.validateType)("FlowType") + } + }); + (0, _utils.default)("QualifiedTypeIdentifier", { + visitor: ["id", "qualification"], + aliases: ["Flow"], + fields: { + id: (0, _utils.validateType)("Identifier"), + qualification: (0, _utils.validateType)(["Identifier", "QualifiedTypeIdentifier"]) + } + }); + (0, _utils.default)("StringLiteralTypeAnnotation", { + builder: ["value"], + aliases: ["Flow", "FlowType"], + fields: { + value: (0, _utils.validate)((0, _utils.assertValueType)("string")) + } + }); + (0, _utils.default)("StringTypeAnnotation", { + aliases: ["Flow", "FlowType", "FlowBaseAnnotation"] + }); + (0, _utils.default)("SymbolTypeAnnotation", { + aliases: ["Flow", "FlowType", "FlowBaseAnnotation"] + }); + (0, _utils.default)("ThisTypeAnnotation", { + aliases: ["Flow", "FlowType", "FlowBaseAnnotation"] + }); + (0, _utils.default)("TupleTypeAnnotation", { + visitor: ["types"], + aliases: ["Flow", "FlowType"], + fields: { + types: (0, _utils.validate)((0, _utils.arrayOfType)("FlowType")) + } + }); + (0, _utils.default)("TypeofTypeAnnotation", { + visitor: ["argument"], + aliases: ["Flow", "FlowType"], + fields: { + argument: (0, _utils.validateType)("FlowType") + } + }); + (0, _utils.default)("TypeAlias", { + visitor: ["id", "typeParameters", "right"], + aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], + fields: { + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), + right: (0, _utils.validateType)("FlowType") + } + }); + (0, _utils.default)("TypeAnnotation", { + aliases: ["Flow"], + visitor: ["typeAnnotation"], + fields: { + typeAnnotation: (0, _utils.validateType)("FlowType") + } + }); + (0, _utils.default)("TypeCastExpression", { + visitor: ["expression", "typeAnnotation"], + aliases: ["Flow", "ExpressionWrapper", "Expression"], + fields: { + expression: (0, _utils.validateType)("Expression"), + typeAnnotation: (0, _utils.validateType)("TypeAnnotation") + } + }); + (0, _utils.default)("TypeParameter", { + aliases: ["Flow"], + visitor: ["bound", "default", "variance"], + fields: { + name: (0, _utils.validate)((0, _utils.assertValueType)("string")), + bound: (0, _utils.validateOptionalType)("TypeAnnotation"), + default: (0, _utils.validateOptionalType)("FlowType"), + variance: (0, _utils.validateOptionalType)("Variance") + } + }); + (0, _utils.default)("TypeParameterDeclaration", { + aliases: ["Flow"], + visitor: ["params"], + fields: { + params: (0, _utils.validate)((0, _utils.arrayOfType)("TypeParameter")) + } + }); + (0, _utils.default)("TypeParameterInstantiation", { + aliases: ["Flow"], + visitor: ["params"], + fields: { + params: (0, _utils.validate)((0, _utils.arrayOfType)("FlowType")) + } + }); + (0, _utils.default)("UnionTypeAnnotation", { + visitor: ["types"], + aliases: ["Flow", "FlowType"], + fields: { + types: (0, _utils.validate)((0, _utils.arrayOfType)("FlowType")) + } + }); + (0, _utils.default)("Variance", { + aliases: ["Flow"], + builder: ["kind"], + fields: { + kind: (0, _utils.validate)((0, _utils.assertOneOf)("minus", "plus")) + } + }); + (0, _utils.default)("VoidTypeAnnotation", { + aliases: ["Flow", "FlowType", "FlowBaseAnnotation"] + }); + (0, _utils.default)("EnumDeclaration", { + aliases: ["Statement", "Declaration"], + visitor: ["id", "body"], + fields: { + id: (0, _utils.validateType)("Identifier"), + body: (0, _utils.validateType)(["EnumBooleanBody", "EnumNumberBody", "EnumStringBody", "EnumSymbolBody"]) + } + }); + (0, _utils.default)("EnumBooleanBody", { + aliases: ["EnumBody"], + visitor: ["members"], + fields: { + explicit: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + members: (0, _utils.validateArrayOfType)("EnumBooleanMember") + } + }); + (0, _utils.default)("EnumNumberBody", { + aliases: ["EnumBody"], + visitor: ["members"], + fields: { + explicit: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + members: (0, _utils.validateArrayOfType)("EnumNumberMember") + } + }); + (0, _utils.default)("EnumStringBody", { + aliases: ["EnumBody"], + visitor: ["members"], + fields: { + explicit: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), + members: (0, _utils.validateArrayOfType)(["EnumStringMember", "EnumDefaultedMember"]) + } + }); + (0, _utils.default)("EnumSymbolBody", { + aliases: ["EnumBody"], + visitor: ["members"], + fields: { + members: (0, _utils.validateArrayOfType)("EnumDefaultedMember") + } + }); + (0, _utils.default)("EnumBooleanMember", { + aliases: ["EnumMember"], + visitor: ["id"], + fields: { + id: (0, _utils.validateType)("Identifier"), + init: (0, _utils.validateType)("BooleanLiteral") + } + }); + (0, _utils.default)("EnumNumberMember", { + aliases: ["EnumMember"], + visitor: ["id", "init"], + fields: { + id: (0, _utils.validateType)("Identifier"), + init: (0, _utils.validateType)("NumericLiteral") + } + }); + (0, _utils.default)("EnumStringMember", { + aliases: ["EnumMember"], + visitor: ["id", "init"], + fields: { + id: (0, _utils.validateType)("Identifier"), + init: (0, _utils.validateType)("StringLiteral") + } + }); + (0, _utils.default)("EnumDefaultedMember", { + aliases: ["EnumMember"], + visitor: ["id"], + fields: { + id: (0, _utils.validateType)("Identifier") + } + }); + }); + + unwrapExports(flow); + + var jsx = createCommonjsModule(function (module) { + + var _utils = _interopRequireWildcard(utils); + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + (0, _utils.default)("JSXAttribute", { + visitor: ["name", "value"], + aliases: ["JSX", "Immutable"], + fields: { + name: { + validate: (0, _utils.assertNodeType)("JSXIdentifier", "JSXNamespacedName") + }, + value: { + optional: true, + validate: (0, _utils.assertNodeType)("JSXElement", "JSXFragment", "StringLiteral", "JSXExpressionContainer") + } + } + }); + (0, _utils.default)("JSXClosingElement", { + visitor: ["name"], + aliases: ["JSX", "Immutable"], + fields: { + name: { + validate: (0, _utils.assertNodeType)("JSXIdentifier", "JSXMemberExpression", "JSXNamespacedName") + } + } + }); + (0, _utils.default)("JSXElement", { + builder: ["openingElement", "closingElement", "children", "selfClosing"], + visitor: ["openingElement", "children", "closingElement"], + aliases: ["JSX", "Immutable", "Expression"], + fields: { + openingElement: { + validate: (0, _utils.assertNodeType)("JSXOpeningElement") + }, + closingElement: { + optional: true, + validate: (0, _utils.assertNodeType)("JSXClosingElement") + }, + children: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("JSXText", "JSXExpressionContainer", "JSXSpreadChild", "JSXElement", "JSXFragment"))) + }, + selfClosing: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + } + } + }); + (0, _utils.default)("JSXEmptyExpression", { + aliases: ["JSX"] + }); + (0, _utils.default)("JSXExpressionContainer", { + visitor: ["expression"], + aliases: ["JSX", "Immutable"], + fields: { + expression: { + validate: (0, _utils.assertNodeType)("Expression", "JSXEmptyExpression") + } + } + }); + (0, _utils.default)("JSXSpreadChild", { + visitor: ["expression"], + aliases: ["JSX", "Immutable"], + fields: { + expression: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + (0, _utils.default)("JSXIdentifier", { + builder: ["name"], + aliases: ["JSX"], + fields: { + name: { + validate: (0, _utils.assertValueType)("string") + } + } + }); + (0, _utils.default)("JSXMemberExpression", { + visitor: ["object", "property"], + aliases: ["JSX"], + fields: { + object: { + validate: (0, _utils.assertNodeType)("JSXMemberExpression", "JSXIdentifier") + }, + property: { + validate: (0, _utils.assertNodeType)("JSXIdentifier") + } + } + }); + (0, _utils.default)("JSXNamespacedName", { + visitor: ["namespace", "name"], + aliases: ["JSX"], + fields: { + namespace: { + validate: (0, _utils.assertNodeType)("JSXIdentifier") + }, + name: { + validate: (0, _utils.assertNodeType)("JSXIdentifier") + } + } + }); + (0, _utils.default)("JSXOpeningElement", { + builder: ["name", "attributes", "selfClosing"], + visitor: ["name", "attributes"], + aliases: ["JSX", "Immutable"], + fields: { + name: { + validate: (0, _utils.assertNodeType)("JSXIdentifier", "JSXMemberExpression", "JSXNamespacedName") + }, + selfClosing: { + default: false + }, + attributes: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("JSXAttribute", "JSXSpreadAttribute"))) + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TypeParameterInstantiation", "TSTypeParameterInstantiation"), + optional: true + } + } + }); + (0, _utils.default)("JSXSpreadAttribute", { + visitor: ["argument"], + aliases: ["JSX"], + fields: { + argument: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + (0, _utils.default)("JSXText", { + aliases: ["JSX", "Immutable"], + builder: ["value"], + fields: { + value: { + validate: (0, _utils.assertValueType)("string") + } + } + }); + (0, _utils.default)("JSXFragment", { + builder: ["openingFragment", "closingFragment", "children"], + visitor: ["openingFragment", "children", "closingFragment"], + aliases: ["JSX", "Immutable", "Expression"], + fields: { + openingFragment: { + validate: (0, _utils.assertNodeType)("JSXOpeningFragment") + }, + closingFragment: { + validate: (0, _utils.assertNodeType)("JSXClosingFragment") + }, + children: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("JSXText", "JSXExpressionContainer", "JSXSpreadChild", "JSXElement", "JSXFragment"))) + } + } + }); + (0, _utils.default)("JSXOpeningFragment", { + aliases: ["JSX", "Immutable"] + }); + (0, _utils.default)("JSXClosingFragment", { + aliases: ["JSX", "Immutable"] + }); + }); + + unwrapExports(jsx); + + var placeholders = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.PLACEHOLDERS_FLIPPED_ALIAS = exports.PLACEHOLDERS_ALIAS = exports.PLACEHOLDERS = void 0; + + + + const PLACEHOLDERS = ["Identifier", "StringLiteral", "Expression", "Statement", "Declaration", "BlockStatement", "ClassBody", "Pattern"]; + exports.PLACEHOLDERS = PLACEHOLDERS; + const PLACEHOLDERS_ALIAS = { + Declaration: ["Statement"], + Pattern: ["PatternLike", "LVal"] + }; + exports.PLACEHOLDERS_ALIAS = PLACEHOLDERS_ALIAS; + + for (const type of PLACEHOLDERS) { + const alias = utils.ALIAS_KEYS[type]; + if (alias == null ? void 0 : alias.length) PLACEHOLDERS_ALIAS[type] = alias; + } + + const PLACEHOLDERS_FLIPPED_ALIAS = {}; + exports.PLACEHOLDERS_FLIPPED_ALIAS = PLACEHOLDERS_FLIPPED_ALIAS; + Object.keys(PLACEHOLDERS_ALIAS).forEach(type => { + PLACEHOLDERS_ALIAS[type].forEach(alias => { + if (!Object.hasOwnProperty.call(PLACEHOLDERS_FLIPPED_ALIAS, alias)) { + PLACEHOLDERS_FLIPPED_ALIAS[alias] = []; + } + + PLACEHOLDERS_FLIPPED_ALIAS[alias].push(type); + }); + }); + }); + + unwrapExports(placeholders); + var placeholders_1 = placeholders.PLACEHOLDERS_FLIPPED_ALIAS; + var placeholders_2 = placeholders.PLACEHOLDERS_ALIAS; + var placeholders_3 = placeholders.PLACEHOLDERS; + + var misc = createCommonjsModule(function (module) { + + var _utils = _interopRequireWildcard(utils); + + + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + (0, _utils.default)("Noop", { + visitor: [] + }); + (0, _utils.default)("Placeholder", { + visitor: [], + builder: ["expectedNode", "name"], + fields: { + name: { + validate: (0, _utils.assertNodeType)("Identifier") + }, + expectedNode: { + validate: (0, _utils.assertOneOf)(...placeholders.PLACEHOLDERS) + } + } + }); + (0, _utils.default)("V8IntrinsicIdentifier", { + builder: ["name"], + fields: { + name: { + validate: (0, _utils.assertValueType)("string") + } + } + }); + }); + + unwrapExports(misc); + + var experimental = createCommonjsModule(function (module) { + + var _utils = _interopRequireWildcard(utils); + + + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + (0, _utils.default)("ArgumentPlaceholder", {}); + (0, _utils.default)("BindExpression", { + visitor: ["object", "callee"], + aliases: ["Expression"], + fields: !process.env.BABEL_TYPES_8_BREAKING ? { + object: { + validate: Object.assign(() => {}, { + oneOfNodeTypes: ["Expression"] + }) + }, + callee: { + validate: Object.assign(() => {}, { + oneOfNodeTypes: ["Expression"] + }) + } + } : { + object: { + validate: (0, _utils.assertNodeType)("Expression") + }, + callee: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + (0, _utils.default)("ClassProperty", { + visitor: ["key", "value", "typeAnnotation", "decorators"], + builder: ["key", "value", "typeAnnotation", "decorators", "computed", "static"], + aliases: ["Property"], + fields: Object.assign({}, core.classMethodOrPropertyCommon, { + value: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + }, + definite: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + typeAnnotation: { + validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"), + optional: true + }, + decorators: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), + optional: true + }, + readonly: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + declare: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + } + }) + }); + (0, _utils.default)("PipelineTopicExpression", { + builder: ["expression"], + visitor: ["expression"], + fields: { + expression: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + (0, _utils.default)("PipelineBareFunction", { + builder: ["callee"], + visitor: ["callee"], + fields: { + callee: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + (0, _utils.default)("PipelinePrimaryTopicReference", { + aliases: ["Expression"] + }); + (0, _utils.default)("ClassPrivateProperty", { + visitor: ["key", "value", "decorators"], + builder: ["key", "value", "decorators", "static"], + aliases: ["Property", "Private"], + fields: { + key: { + validate: (0, _utils.assertNodeType)("PrivateName") + }, + value: { + validate: (0, _utils.assertNodeType)("Expression"), + optional: true + }, + decorators: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), + optional: true + } + } + }); + (0, _utils.default)("ClassPrivateMethod", { + builder: ["kind", "key", "params", "body", "static"], + visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], + aliases: ["Function", "Scopable", "BlockParent", "FunctionParent", "Method", "Private"], + fields: Object.assign({}, core.classMethodOrDeclareMethodCommon, core.functionTypeAnnotationCommon, { + key: { + validate: (0, _utils.assertNodeType)("PrivateName") + }, + body: { + validate: (0, _utils.assertNodeType)("BlockStatement") + } + }) + }); + (0, _utils.default)("ImportAttribute", { + visitor: ["key", "value"], + fields: { + key: { + validate: (0, _utils.assertNodeType)("Identifier", "StringLiteral") + }, + value: { + validate: (0, _utils.assertNodeType)("StringLiteral") + } + } + }); + (0, _utils.default)("Decorator", { + visitor: ["expression"], + fields: { + expression: { + validate: (0, _utils.assertNodeType)("Expression") + } + } + }); + (0, _utils.default)("DoExpression", { + visitor: ["body"], + aliases: ["Expression"], + fields: { + body: { + validate: (0, _utils.assertNodeType)("BlockStatement") + } + } + }); + (0, _utils.default)("ExportDefaultSpecifier", { + visitor: ["exported"], + aliases: ["ModuleSpecifier"], + fields: { + exported: { + validate: (0, _utils.assertNodeType)("Identifier") + } + } + }); + (0, _utils.default)("PrivateName", { + visitor: ["id"], + aliases: ["Private"], + fields: { + id: { + validate: (0, _utils.assertNodeType)("Identifier") + } + } + }); + (0, _utils.default)("RecordExpression", { + visitor: ["properties"], + aliases: ["Expression"], + fields: { + properties: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("ObjectProperty", "SpreadElement"))) + } + } + }); + (0, _utils.default)("TupleExpression", { + fields: { + elements: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Expression", "SpreadElement"))), + default: [] + } + }, + visitor: ["elements"], + aliases: ["Expression"] + }); + (0, _utils.default)("DecimalLiteral", { + builder: ["value"], + fields: { + value: { + validate: (0, _utils.assertValueType)("string") + } + }, + aliases: ["Expression", "Pureish", "Literal", "Immutable"] + }); + (0, _utils.default)("StaticBlock", { + visitor: ["body"], + fields: { + body: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Statement"))) + } + }, + aliases: ["Scopable", "BlockParent"] + }); + }); + + unwrapExports(experimental); + + var typescript = createCommonjsModule(function (module) { + + var _utils = _interopRequireWildcard(utils); + + + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + const bool = (0, _utils.assertValueType)("boolean"); + const tSFunctionTypeAnnotationCommon = { + returnType: { + validate: (0, _utils.assertNodeType)("TSTypeAnnotation", "Noop"), + optional: true + }, + typeParameters: { + validate: (0, _utils.assertNodeType)("TSTypeParameterDeclaration", "Noop"), + optional: true + } + }; + (0, _utils.default)("TSParameterProperty", { + aliases: ["LVal"], + visitor: ["parameter"], + fields: { + accessibility: { + validate: (0, _utils.assertOneOf)("public", "private", "protected"), + optional: true + }, + readonly: { + validate: (0, _utils.assertValueType)("boolean"), + optional: true + }, + parameter: { + validate: (0, _utils.assertNodeType)("Identifier", "AssignmentPattern") + } + } + }); + (0, _utils.default)("TSDeclareFunction", { + aliases: ["Statement", "Declaration"], + visitor: ["id", "typeParameters", "params", "returnType"], + fields: Object.assign({}, core.functionDeclarationCommon, tSFunctionTypeAnnotationCommon) + }); + (0, _utils.default)("TSDeclareMethod", { + visitor: ["decorators", "key", "typeParameters", "params", "returnType"], + fields: Object.assign({}, core.classMethodOrDeclareMethodCommon, tSFunctionTypeAnnotationCommon) + }); + (0, _utils.default)("TSQualifiedName", { + aliases: ["TSEntityName"], + visitor: ["left", "right"], + fields: { + left: (0, _utils.validateType)("TSEntityName"), + right: (0, _utils.validateType)("Identifier") + } + }); + const signatureDeclarationCommon = { + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterDeclaration"), + parameters: (0, _utils.validateArrayOfType)(["Identifier", "RestElement"]), + typeAnnotation: (0, _utils.validateOptionalType)("TSTypeAnnotation") + }; + const callConstructSignatureDeclaration = { + aliases: ["TSTypeElement"], + visitor: ["typeParameters", "parameters", "typeAnnotation"], + fields: signatureDeclarationCommon + }; + (0, _utils.default)("TSCallSignatureDeclaration", callConstructSignatureDeclaration); + (0, _utils.default)("TSConstructSignatureDeclaration", callConstructSignatureDeclaration); + const namedTypeElementCommon = { + key: (0, _utils.validateType)("Expression"), + computed: (0, _utils.validate)(bool), + optional: (0, _utils.validateOptional)(bool) + }; + (0, _utils.default)("TSPropertySignature", { + aliases: ["TSTypeElement"], + visitor: ["key", "typeAnnotation", "initializer"], + fields: Object.assign({}, namedTypeElementCommon, { + readonly: (0, _utils.validateOptional)(bool), + typeAnnotation: (0, _utils.validateOptionalType)("TSTypeAnnotation"), + initializer: (0, _utils.validateOptionalType)("Expression") + }) + }); + (0, _utils.default)("TSMethodSignature", { + aliases: ["TSTypeElement"], + visitor: ["key", "typeParameters", "parameters", "typeAnnotation"], + fields: Object.assign({}, signatureDeclarationCommon, namedTypeElementCommon) + }); + (0, _utils.default)("TSIndexSignature", { + aliases: ["TSTypeElement"], + visitor: ["parameters", "typeAnnotation"], + fields: { + readonly: (0, _utils.validateOptional)(bool), + parameters: (0, _utils.validateArrayOfType)("Identifier"), + typeAnnotation: (0, _utils.validateOptionalType)("TSTypeAnnotation") + } + }); + const tsKeywordTypes = ["TSAnyKeyword", "TSBooleanKeyword", "TSBigIntKeyword", "TSIntrinsicKeyword", "TSNeverKeyword", "TSNullKeyword", "TSNumberKeyword", "TSObjectKeyword", "TSStringKeyword", "TSSymbolKeyword", "TSUndefinedKeyword", "TSUnknownKeyword", "TSVoidKeyword"]; + + for (const type of tsKeywordTypes) { + (0, _utils.default)(type, { + aliases: ["TSType", "TSBaseType"], + visitor: [], + fields: {} + }); + } + + (0, _utils.default)("TSThisType", { + aliases: ["TSType", "TSBaseType"], + visitor: [], + fields: {} + }); + const fnOrCtr = { + aliases: ["TSType"], + visitor: ["typeParameters", "parameters", "typeAnnotation"], + fields: signatureDeclarationCommon + }; + (0, _utils.default)("TSFunctionType", fnOrCtr); + (0, _utils.default)("TSConstructorType", fnOrCtr); + (0, _utils.default)("TSTypeReference", { + aliases: ["TSType"], + visitor: ["typeName", "typeParameters"], + fields: { + typeName: (0, _utils.validateType)("TSEntityName"), + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterInstantiation") + } + }); + (0, _utils.default)("TSTypePredicate", { + aliases: ["TSType"], + visitor: ["parameterName", "typeAnnotation"], + builder: ["parameterName", "typeAnnotation", "asserts"], + fields: { + parameterName: (0, _utils.validateType)(["Identifier", "TSThisType"]), + typeAnnotation: (0, _utils.validateOptionalType)("TSTypeAnnotation"), + asserts: (0, _utils.validateOptional)(bool) + } + }); + (0, _utils.default)("TSTypeQuery", { + aliases: ["TSType"], + visitor: ["exprName"], + fields: { + exprName: (0, _utils.validateType)(["TSEntityName", "TSImportType"]) + } + }); + (0, _utils.default)("TSTypeLiteral", { + aliases: ["TSType"], + visitor: ["members"], + fields: { + members: (0, _utils.validateArrayOfType)("TSTypeElement") + } + }); + (0, _utils.default)("TSArrayType", { + aliases: ["TSType"], + visitor: ["elementType"], + fields: { + elementType: (0, _utils.validateType)("TSType") + } + }); + (0, _utils.default)("TSTupleType", { + aliases: ["TSType"], + visitor: ["elementTypes"], + fields: { + elementTypes: (0, _utils.validateArrayOfType)(["TSType", "TSNamedTupleMember"]) + } + }); + (0, _utils.default)("TSOptionalType", { + aliases: ["TSType"], + visitor: ["typeAnnotation"], + fields: { + typeAnnotation: (0, _utils.validateType)("TSType") + } + }); + (0, _utils.default)("TSRestType", { + aliases: ["TSType"], + visitor: ["typeAnnotation"], + fields: { + typeAnnotation: (0, _utils.validateType)("TSType") + } + }); + (0, _utils.default)("TSNamedTupleMember", { + visitor: ["label", "elementType"], + builder: ["label", "elementType", "optional"], + fields: { + label: (0, _utils.validateType)("Identifier"), + optional: { + validate: bool, + default: false + }, + elementType: (0, _utils.validateType)("TSType") + } + }); + const unionOrIntersection = { + aliases: ["TSType"], + visitor: ["types"], + fields: { + types: (0, _utils.validateArrayOfType)("TSType") + } + }; + (0, _utils.default)("TSUnionType", unionOrIntersection); + (0, _utils.default)("TSIntersectionType", unionOrIntersection); + (0, _utils.default)("TSConditionalType", { + aliases: ["TSType"], + visitor: ["checkType", "extendsType", "trueType", "falseType"], + fields: { + checkType: (0, _utils.validateType)("TSType"), + extendsType: (0, _utils.validateType)("TSType"), + trueType: (0, _utils.validateType)("TSType"), + falseType: (0, _utils.validateType)("TSType") + } + }); + (0, _utils.default)("TSInferType", { + aliases: ["TSType"], + visitor: ["typeParameter"], + fields: { + typeParameter: (0, _utils.validateType)("TSTypeParameter") + } + }); + (0, _utils.default)("TSParenthesizedType", { + aliases: ["TSType"], + visitor: ["typeAnnotation"], + fields: { + typeAnnotation: (0, _utils.validateType)("TSType") + } + }); + (0, _utils.default)("TSTypeOperator", { + aliases: ["TSType"], + visitor: ["typeAnnotation"], + fields: { + operator: (0, _utils.validate)((0, _utils.assertValueType)("string")), + typeAnnotation: (0, _utils.validateType)("TSType") + } + }); + (0, _utils.default)("TSIndexedAccessType", { + aliases: ["TSType"], + visitor: ["objectType", "indexType"], + fields: { + objectType: (0, _utils.validateType)("TSType"), + indexType: (0, _utils.validateType)("TSType") + } + }); + (0, _utils.default)("TSMappedType", { + aliases: ["TSType"], + visitor: ["typeParameter", "typeAnnotation", "nameType"], + fields: { + readonly: (0, _utils.validateOptional)(bool), + typeParameter: (0, _utils.validateType)("TSTypeParameter"), + optional: (0, _utils.validateOptional)(bool), + typeAnnotation: (0, _utils.validateOptionalType)("TSType"), + nameType: (0, _utils.validateOptionalType)("TSType") + } + }); + (0, _utils.default)("TSLiteralType", { + aliases: ["TSType", "TSBaseType"], + visitor: ["literal"], + fields: { + literal: (0, _utils.validateType)(["NumericLiteral", "StringLiteral", "BooleanLiteral", "BigIntLiteral"]) + } + }); + (0, _utils.default)("TSExpressionWithTypeArguments", { + aliases: ["TSType"], + visitor: ["expression", "typeParameters"], + fields: { + expression: (0, _utils.validateType)("TSEntityName"), + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterInstantiation") + } + }); + (0, _utils.default)("TSInterfaceDeclaration", { + aliases: ["Statement", "Declaration"], + visitor: ["id", "typeParameters", "extends", "body"], + fields: { + declare: (0, _utils.validateOptional)(bool), + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterDeclaration"), + extends: (0, _utils.validateOptional)((0, _utils.arrayOfType)("TSExpressionWithTypeArguments")), + body: (0, _utils.validateType)("TSInterfaceBody") + } + }); + (0, _utils.default)("TSInterfaceBody", { + visitor: ["body"], + fields: { + body: (0, _utils.validateArrayOfType)("TSTypeElement") + } + }); + (0, _utils.default)("TSTypeAliasDeclaration", { + aliases: ["Statement", "Declaration"], + visitor: ["id", "typeParameters", "typeAnnotation"], + fields: { + declare: (0, _utils.validateOptional)(bool), + id: (0, _utils.validateType)("Identifier"), + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterDeclaration"), + typeAnnotation: (0, _utils.validateType)("TSType") + } + }); + (0, _utils.default)("TSAsExpression", { + aliases: ["Expression"], + visitor: ["expression", "typeAnnotation"], + fields: { + expression: (0, _utils.validateType)("Expression"), + typeAnnotation: (0, _utils.validateType)("TSType") + } + }); + (0, _utils.default)("TSTypeAssertion", { + aliases: ["Expression"], + visitor: ["typeAnnotation", "expression"], + fields: { + typeAnnotation: (0, _utils.validateType)("TSType"), + expression: (0, _utils.validateType)("Expression") + } + }); + (0, _utils.default)("TSEnumDeclaration", { + aliases: ["Statement", "Declaration"], + visitor: ["id", "members"], + fields: { + declare: (0, _utils.validateOptional)(bool), + const: (0, _utils.validateOptional)(bool), + id: (0, _utils.validateType)("Identifier"), + members: (0, _utils.validateArrayOfType)("TSEnumMember"), + initializer: (0, _utils.validateOptionalType)("Expression") + } + }); + (0, _utils.default)("TSEnumMember", { + visitor: ["id", "initializer"], + fields: { + id: (0, _utils.validateType)(["Identifier", "StringLiteral"]), + initializer: (0, _utils.validateOptionalType)("Expression") + } + }); + (0, _utils.default)("TSModuleDeclaration", { + aliases: ["Statement", "Declaration"], + visitor: ["id", "body"], + fields: { + declare: (0, _utils.validateOptional)(bool), + global: (0, _utils.validateOptional)(bool), + id: (0, _utils.validateType)(["Identifier", "StringLiteral"]), + body: (0, _utils.validateType)(["TSModuleBlock", "TSModuleDeclaration"]) + } + }); + (0, _utils.default)("TSModuleBlock", { + aliases: ["Scopable", "Block", "BlockParent"], + visitor: ["body"], + fields: { + body: (0, _utils.validateArrayOfType)("Statement") + } + }); + (0, _utils.default)("TSImportType", { + aliases: ["TSType"], + visitor: ["argument", "qualifier", "typeParameters"], + fields: { + argument: (0, _utils.validateType)("StringLiteral"), + qualifier: (0, _utils.validateOptionalType)("TSEntityName"), + typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterInstantiation") + } + }); + (0, _utils.default)("TSImportEqualsDeclaration", { + aliases: ["Statement"], + visitor: ["id", "moduleReference"], + fields: { + isExport: (0, _utils.validate)(bool), + id: (0, _utils.validateType)("Identifier"), + moduleReference: (0, _utils.validateType)(["TSEntityName", "TSExternalModuleReference"]) + } + }); + (0, _utils.default)("TSExternalModuleReference", { + visitor: ["expression"], + fields: { + expression: (0, _utils.validateType)("StringLiteral") + } + }); + (0, _utils.default)("TSNonNullExpression", { + aliases: ["Expression"], + visitor: ["expression"], + fields: { + expression: (0, _utils.validateType)("Expression") + } + }); + (0, _utils.default)("TSExportAssignment", { + aliases: ["Statement"], + visitor: ["expression"], + fields: { + expression: (0, _utils.validateType)("Expression") + } + }); + (0, _utils.default)("TSNamespaceExportDeclaration", { + aliases: ["Statement"], + visitor: ["id"], + fields: { + id: (0, _utils.validateType)("Identifier") + } + }); + (0, _utils.default)("TSTypeAnnotation", { + visitor: ["typeAnnotation"], + fields: { + typeAnnotation: { + validate: (0, _utils.assertNodeType)("TSType") + } + } + }); + (0, _utils.default)("TSTypeParameterInstantiation", { + visitor: ["params"], + fields: { + params: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("TSType"))) + } + } + }); + (0, _utils.default)("TSTypeParameterDeclaration", { + visitor: ["params"], + fields: { + params: { + validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("TSTypeParameter"))) + } + } + }); + (0, _utils.default)("TSTypeParameter", { + builder: ["constraint", "default", "name"], + visitor: ["constraint", "default"], + fields: { + name: { + validate: (0, _utils.assertValueType)("string") + }, + constraint: { + validate: (0, _utils.assertNodeType)("TSType"), + optional: true + }, + default: { + validate: (0, _utils.assertNodeType)("TSType"), + optional: true + } + } + }); + }); + + unwrapExports(typescript); + + var definitions = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + Object.defineProperty(exports, "VISITOR_KEYS", { + enumerable: true, + get: function () { + return utils.VISITOR_KEYS; + } + }); + Object.defineProperty(exports, "ALIAS_KEYS", { + enumerable: true, + get: function () { + return utils.ALIAS_KEYS; + } + }); + Object.defineProperty(exports, "FLIPPED_ALIAS_KEYS", { + enumerable: true, + get: function () { + return utils.FLIPPED_ALIAS_KEYS; + } + }); + Object.defineProperty(exports, "NODE_FIELDS", { + enumerable: true, + get: function () { + return utils.NODE_FIELDS; + } + }); + Object.defineProperty(exports, "BUILDER_KEYS", { + enumerable: true, + get: function () { + return utils.BUILDER_KEYS; + } + }); + Object.defineProperty(exports, "DEPRECATED_KEYS", { + enumerable: true, + get: function () { + return utils.DEPRECATED_KEYS; + } + }); + Object.defineProperty(exports, "NODE_PARENT_VALIDATIONS", { + enumerable: true, + get: function () { + return utils.NODE_PARENT_VALIDATIONS; + } + }); + Object.defineProperty(exports, "PLACEHOLDERS", { + enumerable: true, + get: function () { + return placeholders.PLACEHOLDERS; + } + }); + Object.defineProperty(exports, "PLACEHOLDERS_ALIAS", { + enumerable: true, + get: function () { + return placeholders.PLACEHOLDERS_ALIAS; + } + }); + Object.defineProperty(exports, "PLACEHOLDERS_FLIPPED_ALIAS", { + enumerable: true, + get: function () { + return placeholders.PLACEHOLDERS_FLIPPED_ALIAS; + } + }); + exports.TYPES = void 0; + + var _toFastProperties = _interopRequireDefault(toFastProperties); + + + + + + + + + + + + + + + + + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + (0, _toFastProperties.default)(utils.VISITOR_KEYS); + (0, _toFastProperties.default)(utils.ALIAS_KEYS); + (0, _toFastProperties.default)(utils.FLIPPED_ALIAS_KEYS); + (0, _toFastProperties.default)(utils.NODE_FIELDS); + (0, _toFastProperties.default)(utils.BUILDER_KEYS); + (0, _toFastProperties.default)(utils.DEPRECATED_KEYS); + (0, _toFastProperties.default)(placeholders.PLACEHOLDERS_ALIAS); + (0, _toFastProperties.default)(placeholders.PLACEHOLDERS_FLIPPED_ALIAS); + const TYPES = Object.keys(utils.VISITOR_KEYS).concat(Object.keys(utils.FLIPPED_ALIAS_KEYS)).concat(Object.keys(utils.DEPRECATED_KEYS)); + exports.TYPES = TYPES; + }); + + unwrapExports(definitions); + var definitions_1 = definitions.TYPES; + + var builder_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = builder; + + var _clone = _interopRequireDefault(clone_1); + + + + var _validate = _interopRequireDefault(validate_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function builder(type, ...args) { + const keys = definitions.BUILDER_KEYS[type]; + const countArgs = args.length; + + if (countArgs > keys.length) { + throw new Error(`${type}: Too many arguments passed. Received ${countArgs} but can receive no more than ${keys.length}`); + } + + const node = { + type + }; + let i = 0; + keys.forEach(key => { + const field = definitions.NODE_FIELDS[type][key]; + let arg; + if (i < countArgs) arg = args[i]; + if (arg === undefined) arg = (0, _clone.default)(field.default); + node[key] = arg; + i++; + }); + + for (const key of Object.keys(node)) { + (0, _validate.default)(node, key, node[key]); + } + + return node; + } + }); + + unwrapExports(builder_1); + + var generated$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.ArrayExpression = exports.arrayExpression = arrayExpression; + exports.AssignmentExpression = exports.assignmentExpression = assignmentExpression; + exports.BinaryExpression = exports.binaryExpression = binaryExpression; + exports.InterpreterDirective = exports.interpreterDirective = interpreterDirective; + exports.Directive = exports.directive = directive; + exports.DirectiveLiteral = exports.directiveLiteral = directiveLiteral; + exports.BlockStatement = exports.blockStatement = blockStatement; + exports.BreakStatement = exports.breakStatement = breakStatement; + exports.CallExpression = exports.callExpression = callExpression; + exports.CatchClause = exports.catchClause = catchClause; + exports.ConditionalExpression = exports.conditionalExpression = conditionalExpression; + exports.ContinueStatement = exports.continueStatement = continueStatement; + exports.DebuggerStatement = exports.debuggerStatement = debuggerStatement; + exports.DoWhileStatement = exports.doWhileStatement = doWhileStatement; + exports.EmptyStatement = exports.emptyStatement = emptyStatement; + exports.ExpressionStatement = exports.expressionStatement = expressionStatement; + exports.File = exports.file = file; + exports.ForInStatement = exports.forInStatement = forInStatement; + exports.ForStatement = exports.forStatement = forStatement; + exports.FunctionDeclaration = exports.functionDeclaration = functionDeclaration; + exports.FunctionExpression = exports.functionExpression = functionExpression; + exports.Identifier = exports.identifier = identifier; + exports.IfStatement = exports.ifStatement = ifStatement; + exports.LabeledStatement = exports.labeledStatement = labeledStatement; + exports.StringLiteral = exports.stringLiteral = stringLiteral; + exports.NumericLiteral = exports.numericLiteral = numericLiteral; + exports.NullLiteral = exports.nullLiteral = nullLiteral; + exports.BooleanLiteral = exports.booleanLiteral = booleanLiteral; + exports.RegExpLiteral = exports.regExpLiteral = regExpLiteral; + exports.LogicalExpression = exports.logicalExpression = logicalExpression; + exports.MemberExpression = exports.memberExpression = memberExpression; + exports.NewExpression = exports.newExpression = newExpression; + exports.Program = exports.program = program; + exports.ObjectExpression = exports.objectExpression = objectExpression; + exports.ObjectMethod = exports.objectMethod = objectMethod; + exports.ObjectProperty = exports.objectProperty = objectProperty; + exports.RestElement = exports.restElement = restElement; + exports.ReturnStatement = exports.returnStatement = returnStatement; + exports.SequenceExpression = exports.sequenceExpression = sequenceExpression; + exports.ParenthesizedExpression = exports.parenthesizedExpression = parenthesizedExpression; + exports.SwitchCase = exports.switchCase = switchCase; + exports.SwitchStatement = exports.switchStatement = switchStatement; + exports.ThisExpression = exports.thisExpression = thisExpression; + exports.ThrowStatement = exports.throwStatement = throwStatement; + exports.TryStatement = exports.tryStatement = tryStatement; + exports.UnaryExpression = exports.unaryExpression = unaryExpression; + exports.UpdateExpression = exports.updateExpression = updateExpression; + exports.VariableDeclaration = exports.variableDeclaration = variableDeclaration; + exports.VariableDeclarator = exports.variableDeclarator = variableDeclarator; + exports.WhileStatement = exports.whileStatement = whileStatement; + exports.WithStatement = exports.withStatement = withStatement; + exports.AssignmentPattern = exports.assignmentPattern = assignmentPattern; + exports.ArrayPattern = exports.arrayPattern = arrayPattern; + exports.ArrowFunctionExpression = exports.arrowFunctionExpression = arrowFunctionExpression; + exports.ClassBody = exports.classBody = classBody; + exports.ClassExpression = exports.classExpression = classExpression; + exports.ClassDeclaration = exports.classDeclaration = classDeclaration; + exports.ExportAllDeclaration = exports.exportAllDeclaration = exportAllDeclaration; + exports.ExportDefaultDeclaration = exports.exportDefaultDeclaration = exportDefaultDeclaration; + exports.ExportNamedDeclaration = exports.exportNamedDeclaration = exportNamedDeclaration; + exports.ExportSpecifier = exports.exportSpecifier = exportSpecifier; + exports.ForOfStatement = exports.forOfStatement = forOfStatement; + exports.ImportDeclaration = exports.importDeclaration = importDeclaration; + exports.ImportDefaultSpecifier = exports.importDefaultSpecifier = importDefaultSpecifier; + exports.ImportNamespaceSpecifier = exports.importNamespaceSpecifier = importNamespaceSpecifier; + exports.ImportSpecifier = exports.importSpecifier = importSpecifier; + exports.MetaProperty = exports.metaProperty = metaProperty; + exports.ClassMethod = exports.classMethod = classMethod; + exports.ObjectPattern = exports.objectPattern = objectPattern; + exports.SpreadElement = exports.spreadElement = spreadElement; + exports.super = exports.Super = _super; + exports.TaggedTemplateExpression = exports.taggedTemplateExpression = taggedTemplateExpression; + exports.TemplateElement = exports.templateElement = templateElement; + exports.TemplateLiteral = exports.templateLiteral = templateLiteral; + exports.YieldExpression = exports.yieldExpression = yieldExpression; + exports.AwaitExpression = exports.awaitExpression = awaitExpression; + exports.import = exports.Import = _import; + exports.BigIntLiteral = exports.bigIntLiteral = bigIntLiteral; + exports.ExportNamespaceSpecifier = exports.exportNamespaceSpecifier = exportNamespaceSpecifier; + exports.OptionalMemberExpression = exports.optionalMemberExpression = optionalMemberExpression; + exports.OptionalCallExpression = exports.optionalCallExpression = optionalCallExpression; + exports.AnyTypeAnnotation = exports.anyTypeAnnotation = anyTypeAnnotation; + exports.ArrayTypeAnnotation = exports.arrayTypeAnnotation = arrayTypeAnnotation; + exports.BooleanTypeAnnotation = exports.booleanTypeAnnotation = booleanTypeAnnotation; + exports.BooleanLiteralTypeAnnotation = exports.booleanLiteralTypeAnnotation = booleanLiteralTypeAnnotation; + exports.NullLiteralTypeAnnotation = exports.nullLiteralTypeAnnotation = nullLiteralTypeAnnotation; + exports.ClassImplements = exports.classImplements = classImplements; + exports.DeclareClass = exports.declareClass = declareClass; + exports.DeclareFunction = exports.declareFunction = declareFunction; + exports.DeclareInterface = exports.declareInterface = declareInterface; + exports.DeclareModule = exports.declareModule = declareModule; + exports.DeclareModuleExports = exports.declareModuleExports = declareModuleExports; + exports.DeclareTypeAlias = exports.declareTypeAlias = declareTypeAlias; + exports.DeclareOpaqueType = exports.declareOpaqueType = declareOpaqueType; + exports.DeclareVariable = exports.declareVariable = declareVariable; + exports.DeclareExportDeclaration = exports.declareExportDeclaration = declareExportDeclaration; + exports.DeclareExportAllDeclaration = exports.declareExportAllDeclaration = declareExportAllDeclaration; + exports.DeclaredPredicate = exports.declaredPredicate = declaredPredicate; + exports.ExistsTypeAnnotation = exports.existsTypeAnnotation = existsTypeAnnotation; + exports.FunctionTypeAnnotation = exports.functionTypeAnnotation = functionTypeAnnotation; + exports.FunctionTypeParam = exports.functionTypeParam = functionTypeParam; + exports.GenericTypeAnnotation = exports.genericTypeAnnotation = genericTypeAnnotation; + exports.InferredPredicate = exports.inferredPredicate = inferredPredicate; + exports.InterfaceExtends = exports.interfaceExtends = interfaceExtends; + exports.InterfaceDeclaration = exports.interfaceDeclaration = interfaceDeclaration; + exports.InterfaceTypeAnnotation = exports.interfaceTypeAnnotation = interfaceTypeAnnotation; + exports.IntersectionTypeAnnotation = exports.intersectionTypeAnnotation = intersectionTypeAnnotation; + exports.MixedTypeAnnotation = exports.mixedTypeAnnotation = mixedTypeAnnotation; + exports.EmptyTypeAnnotation = exports.emptyTypeAnnotation = emptyTypeAnnotation; + exports.NullableTypeAnnotation = exports.nullableTypeAnnotation = nullableTypeAnnotation; + exports.NumberLiteralTypeAnnotation = exports.numberLiteralTypeAnnotation = numberLiteralTypeAnnotation; + exports.NumberTypeAnnotation = exports.numberTypeAnnotation = numberTypeAnnotation; + exports.ObjectTypeAnnotation = exports.objectTypeAnnotation = objectTypeAnnotation; + exports.ObjectTypeInternalSlot = exports.objectTypeInternalSlot = objectTypeInternalSlot; + exports.ObjectTypeCallProperty = exports.objectTypeCallProperty = objectTypeCallProperty; + exports.ObjectTypeIndexer = exports.objectTypeIndexer = objectTypeIndexer; + exports.ObjectTypeProperty = exports.objectTypeProperty = objectTypeProperty; + exports.ObjectTypeSpreadProperty = exports.objectTypeSpreadProperty = objectTypeSpreadProperty; + exports.OpaqueType = exports.opaqueType = opaqueType; + exports.QualifiedTypeIdentifier = exports.qualifiedTypeIdentifier = qualifiedTypeIdentifier; + exports.StringLiteralTypeAnnotation = exports.stringLiteralTypeAnnotation = stringLiteralTypeAnnotation; + exports.StringTypeAnnotation = exports.stringTypeAnnotation = stringTypeAnnotation; + exports.SymbolTypeAnnotation = exports.symbolTypeAnnotation = symbolTypeAnnotation; + exports.ThisTypeAnnotation = exports.thisTypeAnnotation = thisTypeAnnotation; + exports.TupleTypeAnnotation = exports.tupleTypeAnnotation = tupleTypeAnnotation; + exports.TypeofTypeAnnotation = exports.typeofTypeAnnotation = typeofTypeAnnotation; + exports.TypeAlias = exports.typeAlias = typeAlias; + exports.TypeAnnotation = exports.typeAnnotation = typeAnnotation; + exports.TypeCastExpression = exports.typeCastExpression = typeCastExpression; + exports.TypeParameter = exports.typeParameter = typeParameter; + exports.TypeParameterDeclaration = exports.typeParameterDeclaration = typeParameterDeclaration; + exports.TypeParameterInstantiation = exports.typeParameterInstantiation = typeParameterInstantiation; + exports.UnionTypeAnnotation = exports.unionTypeAnnotation = unionTypeAnnotation; + exports.Variance = exports.variance = variance; + exports.VoidTypeAnnotation = exports.voidTypeAnnotation = voidTypeAnnotation; + exports.EnumDeclaration = exports.enumDeclaration = enumDeclaration; + exports.EnumBooleanBody = exports.enumBooleanBody = enumBooleanBody; + exports.EnumNumberBody = exports.enumNumberBody = enumNumberBody; + exports.EnumStringBody = exports.enumStringBody = enumStringBody; + exports.EnumSymbolBody = exports.enumSymbolBody = enumSymbolBody; + exports.EnumBooleanMember = exports.enumBooleanMember = enumBooleanMember; + exports.EnumNumberMember = exports.enumNumberMember = enumNumberMember; + exports.EnumStringMember = exports.enumStringMember = enumStringMember; + exports.EnumDefaultedMember = exports.enumDefaultedMember = enumDefaultedMember; + exports.jSXAttribute = exports.JSXAttribute = exports.jsxAttribute = jsxAttribute; + exports.jSXClosingElement = exports.JSXClosingElement = exports.jsxClosingElement = jsxClosingElement; + exports.jSXElement = exports.JSXElement = exports.jsxElement = jsxElement; + exports.jSXEmptyExpression = exports.JSXEmptyExpression = exports.jsxEmptyExpression = jsxEmptyExpression; + exports.jSXExpressionContainer = exports.JSXExpressionContainer = exports.jsxExpressionContainer = jsxExpressionContainer; + exports.jSXSpreadChild = exports.JSXSpreadChild = exports.jsxSpreadChild = jsxSpreadChild; + exports.jSXIdentifier = exports.JSXIdentifier = exports.jsxIdentifier = jsxIdentifier; + exports.jSXMemberExpression = exports.JSXMemberExpression = exports.jsxMemberExpression = jsxMemberExpression; + exports.jSXNamespacedName = exports.JSXNamespacedName = exports.jsxNamespacedName = jsxNamespacedName; + exports.jSXOpeningElement = exports.JSXOpeningElement = exports.jsxOpeningElement = jsxOpeningElement; + exports.jSXSpreadAttribute = exports.JSXSpreadAttribute = exports.jsxSpreadAttribute = jsxSpreadAttribute; + exports.jSXText = exports.JSXText = exports.jsxText = jsxText; + exports.jSXFragment = exports.JSXFragment = exports.jsxFragment = jsxFragment; + exports.jSXOpeningFragment = exports.JSXOpeningFragment = exports.jsxOpeningFragment = jsxOpeningFragment; + exports.jSXClosingFragment = exports.JSXClosingFragment = exports.jsxClosingFragment = jsxClosingFragment; + exports.Noop = exports.noop = noop; + exports.Placeholder = exports.placeholder = placeholder; + exports.V8IntrinsicIdentifier = exports.v8IntrinsicIdentifier = v8IntrinsicIdentifier; + exports.ArgumentPlaceholder = exports.argumentPlaceholder = argumentPlaceholder; + exports.BindExpression = exports.bindExpression = bindExpression; + exports.ClassProperty = exports.classProperty = classProperty; + exports.PipelineTopicExpression = exports.pipelineTopicExpression = pipelineTopicExpression; + exports.PipelineBareFunction = exports.pipelineBareFunction = pipelineBareFunction; + exports.PipelinePrimaryTopicReference = exports.pipelinePrimaryTopicReference = pipelinePrimaryTopicReference; + exports.ClassPrivateProperty = exports.classPrivateProperty = classPrivateProperty; + exports.ClassPrivateMethod = exports.classPrivateMethod = classPrivateMethod; + exports.ImportAttribute = exports.importAttribute = importAttribute; + exports.Decorator = exports.decorator = decorator; + exports.DoExpression = exports.doExpression = doExpression; + exports.ExportDefaultSpecifier = exports.exportDefaultSpecifier = exportDefaultSpecifier; + exports.PrivateName = exports.privateName = privateName; + exports.RecordExpression = exports.recordExpression = recordExpression; + exports.TupleExpression = exports.tupleExpression = tupleExpression; + exports.DecimalLiteral = exports.decimalLiteral = decimalLiteral; + exports.StaticBlock = exports.staticBlock = staticBlock; + exports.tSParameterProperty = exports.TSParameterProperty = exports.tsParameterProperty = tsParameterProperty; + exports.tSDeclareFunction = exports.TSDeclareFunction = exports.tsDeclareFunction = tsDeclareFunction; + exports.tSDeclareMethod = exports.TSDeclareMethod = exports.tsDeclareMethod = tsDeclareMethod; + exports.tSQualifiedName = exports.TSQualifiedName = exports.tsQualifiedName = tsQualifiedName; + exports.tSCallSignatureDeclaration = exports.TSCallSignatureDeclaration = exports.tsCallSignatureDeclaration = tsCallSignatureDeclaration; + exports.tSConstructSignatureDeclaration = exports.TSConstructSignatureDeclaration = exports.tsConstructSignatureDeclaration = tsConstructSignatureDeclaration; + exports.tSPropertySignature = exports.TSPropertySignature = exports.tsPropertySignature = tsPropertySignature; + exports.tSMethodSignature = exports.TSMethodSignature = exports.tsMethodSignature = tsMethodSignature; + exports.tSIndexSignature = exports.TSIndexSignature = exports.tsIndexSignature = tsIndexSignature; + exports.tSAnyKeyword = exports.TSAnyKeyword = exports.tsAnyKeyword = tsAnyKeyword; + exports.tSBooleanKeyword = exports.TSBooleanKeyword = exports.tsBooleanKeyword = tsBooleanKeyword; + exports.tSBigIntKeyword = exports.TSBigIntKeyword = exports.tsBigIntKeyword = tsBigIntKeyword; + exports.tSIntrinsicKeyword = exports.TSIntrinsicKeyword = exports.tsIntrinsicKeyword = tsIntrinsicKeyword; + exports.tSNeverKeyword = exports.TSNeverKeyword = exports.tsNeverKeyword = tsNeverKeyword; + exports.tSNullKeyword = exports.TSNullKeyword = exports.tsNullKeyword = tsNullKeyword; + exports.tSNumberKeyword = exports.TSNumberKeyword = exports.tsNumberKeyword = tsNumberKeyword; + exports.tSObjectKeyword = exports.TSObjectKeyword = exports.tsObjectKeyword = tsObjectKeyword; + exports.tSStringKeyword = exports.TSStringKeyword = exports.tsStringKeyword = tsStringKeyword; + exports.tSSymbolKeyword = exports.TSSymbolKeyword = exports.tsSymbolKeyword = tsSymbolKeyword; + exports.tSUndefinedKeyword = exports.TSUndefinedKeyword = exports.tsUndefinedKeyword = tsUndefinedKeyword; + exports.tSUnknownKeyword = exports.TSUnknownKeyword = exports.tsUnknownKeyword = tsUnknownKeyword; + exports.tSVoidKeyword = exports.TSVoidKeyword = exports.tsVoidKeyword = tsVoidKeyword; + exports.tSThisType = exports.TSThisType = exports.tsThisType = tsThisType; + exports.tSFunctionType = exports.TSFunctionType = exports.tsFunctionType = tsFunctionType; + exports.tSConstructorType = exports.TSConstructorType = exports.tsConstructorType = tsConstructorType; + exports.tSTypeReference = exports.TSTypeReference = exports.tsTypeReference = tsTypeReference; + exports.tSTypePredicate = exports.TSTypePredicate = exports.tsTypePredicate = tsTypePredicate; + exports.tSTypeQuery = exports.TSTypeQuery = exports.tsTypeQuery = tsTypeQuery; + exports.tSTypeLiteral = exports.TSTypeLiteral = exports.tsTypeLiteral = tsTypeLiteral; + exports.tSArrayType = exports.TSArrayType = exports.tsArrayType = tsArrayType; + exports.tSTupleType = exports.TSTupleType = exports.tsTupleType = tsTupleType; + exports.tSOptionalType = exports.TSOptionalType = exports.tsOptionalType = tsOptionalType; + exports.tSRestType = exports.TSRestType = exports.tsRestType = tsRestType; + exports.tSNamedTupleMember = exports.TSNamedTupleMember = exports.tsNamedTupleMember = tsNamedTupleMember; + exports.tSUnionType = exports.TSUnionType = exports.tsUnionType = tsUnionType; + exports.tSIntersectionType = exports.TSIntersectionType = exports.tsIntersectionType = tsIntersectionType; + exports.tSConditionalType = exports.TSConditionalType = exports.tsConditionalType = tsConditionalType; + exports.tSInferType = exports.TSInferType = exports.tsInferType = tsInferType; + exports.tSParenthesizedType = exports.TSParenthesizedType = exports.tsParenthesizedType = tsParenthesizedType; + exports.tSTypeOperator = exports.TSTypeOperator = exports.tsTypeOperator = tsTypeOperator; + exports.tSIndexedAccessType = exports.TSIndexedAccessType = exports.tsIndexedAccessType = tsIndexedAccessType; + exports.tSMappedType = exports.TSMappedType = exports.tsMappedType = tsMappedType; + exports.tSLiteralType = exports.TSLiteralType = exports.tsLiteralType = tsLiteralType; + exports.tSExpressionWithTypeArguments = exports.TSExpressionWithTypeArguments = exports.tsExpressionWithTypeArguments = tsExpressionWithTypeArguments; + exports.tSInterfaceDeclaration = exports.TSInterfaceDeclaration = exports.tsInterfaceDeclaration = tsInterfaceDeclaration; + exports.tSInterfaceBody = exports.TSInterfaceBody = exports.tsInterfaceBody = tsInterfaceBody; + exports.tSTypeAliasDeclaration = exports.TSTypeAliasDeclaration = exports.tsTypeAliasDeclaration = tsTypeAliasDeclaration; + exports.tSAsExpression = exports.TSAsExpression = exports.tsAsExpression = tsAsExpression; + exports.tSTypeAssertion = exports.TSTypeAssertion = exports.tsTypeAssertion = tsTypeAssertion; + exports.tSEnumDeclaration = exports.TSEnumDeclaration = exports.tsEnumDeclaration = tsEnumDeclaration; + exports.tSEnumMember = exports.TSEnumMember = exports.tsEnumMember = tsEnumMember; + exports.tSModuleDeclaration = exports.TSModuleDeclaration = exports.tsModuleDeclaration = tsModuleDeclaration; + exports.tSModuleBlock = exports.TSModuleBlock = exports.tsModuleBlock = tsModuleBlock; + exports.tSImportType = exports.TSImportType = exports.tsImportType = tsImportType; + exports.tSImportEqualsDeclaration = exports.TSImportEqualsDeclaration = exports.tsImportEqualsDeclaration = tsImportEqualsDeclaration; + exports.tSExternalModuleReference = exports.TSExternalModuleReference = exports.tsExternalModuleReference = tsExternalModuleReference; + exports.tSNonNullExpression = exports.TSNonNullExpression = exports.tsNonNullExpression = tsNonNullExpression; + exports.tSExportAssignment = exports.TSExportAssignment = exports.tsExportAssignment = tsExportAssignment; + exports.tSNamespaceExportDeclaration = exports.TSNamespaceExportDeclaration = exports.tsNamespaceExportDeclaration = tsNamespaceExportDeclaration; + exports.tSTypeAnnotation = exports.TSTypeAnnotation = exports.tsTypeAnnotation = tsTypeAnnotation; + exports.tSTypeParameterInstantiation = exports.TSTypeParameterInstantiation = exports.tsTypeParameterInstantiation = tsTypeParameterInstantiation; + exports.tSTypeParameterDeclaration = exports.TSTypeParameterDeclaration = exports.tsTypeParameterDeclaration = tsTypeParameterDeclaration; + exports.tSTypeParameter = exports.TSTypeParameter = exports.tsTypeParameter = tsTypeParameter; + exports.numberLiteral = exports.NumberLiteral = NumberLiteral; + exports.regexLiteral = exports.RegexLiteral = RegexLiteral; + exports.restProperty = exports.RestProperty = RestProperty; + exports.spreadProperty = exports.SpreadProperty = SpreadProperty; + + var _builder = _interopRequireDefault(builder_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function arrayExpression(...args) { + return (0, _builder.default)("ArrayExpression", ...args); + } + + function assignmentExpression(...args) { + return (0, _builder.default)("AssignmentExpression", ...args); + } + + function binaryExpression(...args) { + return (0, _builder.default)("BinaryExpression", ...args); + } + + function interpreterDirective(...args) { + return (0, _builder.default)("InterpreterDirective", ...args); + } + + function directive(...args) { + return (0, _builder.default)("Directive", ...args); + } + + function directiveLiteral(...args) { + return (0, _builder.default)("DirectiveLiteral", ...args); + } + + function blockStatement(...args) { + return (0, _builder.default)("BlockStatement", ...args); + } + + function breakStatement(...args) { + return (0, _builder.default)("BreakStatement", ...args); + } + + function callExpression(...args) { + return (0, _builder.default)("CallExpression", ...args); + } + + function catchClause(...args) { + return (0, _builder.default)("CatchClause", ...args); + } + + function conditionalExpression(...args) { + return (0, _builder.default)("ConditionalExpression", ...args); + } + + function continueStatement(...args) { + return (0, _builder.default)("ContinueStatement", ...args); + } + + function debuggerStatement(...args) { + return (0, _builder.default)("DebuggerStatement", ...args); + } + + function doWhileStatement(...args) { + return (0, _builder.default)("DoWhileStatement", ...args); + } + + function emptyStatement(...args) { + return (0, _builder.default)("EmptyStatement", ...args); + } + + function expressionStatement(...args) { + return (0, _builder.default)("ExpressionStatement", ...args); + } + + function file(...args) { + return (0, _builder.default)("File", ...args); + } + + function forInStatement(...args) { + return (0, _builder.default)("ForInStatement", ...args); + } + + function forStatement(...args) { + return (0, _builder.default)("ForStatement", ...args); + } + + function functionDeclaration(...args) { + return (0, _builder.default)("FunctionDeclaration", ...args); + } + + function functionExpression(...args) { + return (0, _builder.default)("FunctionExpression", ...args); + } + + function identifier(...args) { + return (0, _builder.default)("Identifier", ...args); + } + + function ifStatement(...args) { + return (0, _builder.default)("IfStatement", ...args); + } + + function labeledStatement(...args) { + return (0, _builder.default)("LabeledStatement", ...args); + } + + function stringLiteral(...args) { + return (0, _builder.default)("StringLiteral", ...args); + } + + function numericLiteral(...args) { + return (0, _builder.default)("NumericLiteral", ...args); + } + + function nullLiteral(...args) { + return (0, _builder.default)("NullLiteral", ...args); + } + + function booleanLiteral(...args) { + return (0, _builder.default)("BooleanLiteral", ...args); + } + + function regExpLiteral(...args) { + return (0, _builder.default)("RegExpLiteral", ...args); + } + + function logicalExpression(...args) { + return (0, _builder.default)("LogicalExpression", ...args); + } + + function memberExpression(...args) { + return (0, _builder.default)("MemberExpression", ...args); + } + + function newExpression(...args) { + return (0, _builder.default)("NewExpression", ...args); + } + + function program(...args) { + return (0, _builder.default)("Program", ...args); + } + + function objectExpression(...args) { + return (0, _builder.default)("ObjectExpression", ...args); + } + + function objectMethod(...args) { + return (0, _builder.default)("ObjectMethod", ...args); + } + + function objectProperty(...args) { + return (0, _builder.default)("ObjectProperty", ...args); + } + + function restElement(...args) { + return (0, _builder.default)("RestElement", ...args); + } + + function returnStatement(...args) { + return (0, _builder.default)("ReturnStatement", ...args); + } + + function sequenceExpression(...args) { + return (0, _builder.default)("SequenceExpression", ...args); + } + + function parenthesizedExpression(...args) { + return (0, _builder.default)("ParenthesizedExpression", ...args); + } + + function switchCase(...args) { + return (0, _builder.default)("SwitchCase", ...args); + } + + function switchStatement(...args) { + return (0, _builder.default)("SwitchStatement", ...args); + } + + function thisExpression(...args) { + return (0, _builder.default)("ThisExpression", ...args); + } + + function throwStatement(...args) { + return (0, _builder.default)("ThrowStatement", ...args); + } + + function tryStatement(...args) { + return (0, _builder.default)("TryStatement", ...args); + } + + function unaryExpression(...args) { + return (0, _builder.default)("UnaryExpression", ...args); + } + + function updateExpression(...args) { + return (0, _builder.default)("UpdateExpression", ...args); + } + + function variableDeclaration(...args) { + return (0, _builder.default)("VariableDeclaration", ...args); + } + + function variableDeclarator(...args) { + return (0, _builder.default)("VariableDeclarator", ...args); + } + + function whileStatement(...args) { + return (0, _builder.default)("WhileStatement", ...args); + } + + function withStatement(...args) { + return (0, _builder.default)("WithStatement", ...args); + } + + function assignmentPattern(...args) { + return (0, _builder.default)("AssignmentPattern", ...args); + } + + function arrayPattern(...args) { + return (0, _builder.default)("ArrayPattern", ...args); + } + + function arrowFunctionExpression(...args) { + return (0, _builder.default)("ArrowFunctionExpression", ...args); + } + + function classBody(...args) { + return (0, _builder.default)("ClassBody", ...args); + } + + function classExpression(...args) { + return (0, _builder.default)("ClassExpression", ...args); + } + + function classDeclaration(...args) { + return (0, _builder.default)("ClassDeclaration", ...args); + } + + function exportAllDeclaration(...args) { + return (0, _builder.default)("ExportAllDeclaration", ...args); + } + + function exportDefaultDeclaration(...args) { + return (0, _builder.default)("ExportDefaultDeclaration", ...args); + } + + function exportNamedDeclaration(...args) { + return (0, _builder.default)("ExportNamedDeclaration", ...args); + } + + function exportSpecifier(...args) { + return (0, _builder.default)("ExportSpecifier", ...args); + } + + function forOfStatement(...args) { + return (0, _builder.default)("ForOfStatement", ...args); + } + + function importDeclaration(...args) { + return (0, _builder.default)("ImportDeclaration", ...args); + } + + function importDefaultSpecifier(...args) { + return (0, _builder.default)("ImportDefaultSpecifier", ...args); + } + + function importNamespaceSpecifier(...args) { + return (0, _builder.default)("ImportNamespaceSpecifier", ...args); + } + + function importSpecifier(...args) { + return (0, _builder.default)("ImportSpecifier", ...args); + } + + function metaProperty(...args) { + return (0, _builder.default)("MetaProperty", ...args); + } + + function classMethod(...args) { + return (0, _builder.default)("ClassMethod", ...args); + } + + function objectPattern(...args) { + return (0, _builder.default)("ObjectPattern", ...args); + } + + function spreadElement(...args) { + return (0, _builder.default)("SpreadElement", ...args); + } + + function _super(...args) { + return (0, _builder.default)("Super", ...args); + } + + function taggedTemplateExpression(...args) { + return (0, _builder.default)("TaggedTemplateExpression", ...args); + } + + function templateElement(...args) { + return (0, _builder.default)("TemplateElement", ...args); + } + + function templateLiteral(...args) { + return (0, _builder.default)("TemplateLiteral", ...args); + } + + function yieldExpression(...args) { + return (0, _builder.default)("YieldExpression", ...args); + } + + function awaitExpression(...args) { + return (0, _builder.default)("AwaitExpression", ...args); + } + + function _import(...args) { + return (0, _builder.default)("Import", ...args); + } + + function bigIntLiteral(...args) { + return (0, _builder.default)("BigIntLiteral", ...args); + } + + function exportNamespaceSpecifier(...args) { + return (0, _builder.default)("ExportNamespaceSpecifier", ...args); + } + + function optionalMemberExpression(...args) { + return (0, _builder.default)("OptionalMemberExpression", ...args); + } + + function optionalCallExpression(...args) { + return (0, _builder.default)("OptionalCallExpression", ...args); + } + + function anyTypeAnnotation(...args) { + return (0, _builder.default)("AnyTypeAnnotation", ...args); + } + + function arrayTypeAnnotation(...args) { + return (0, _builder.default)("ArrayTypeAnnotation", ...args); + } + + function booleanTypeAnnotation(...args) { + return (0, _builder.default)("BooleanTypeAnnotation", ...args); + } + + function booleanLiteralTypeAnnotation(...args) { + return (0, _builder.default)("BooleanLiteralTypeAnnotation", ...args); + } + + function nullLiteralTypeAnnotation(...args) { + return (0, _builder.default)("NullLiteralTypeAnnotation", ...args); + } + + function classImplements(...args) { + return (0, _builder.default)("ClassImplements", ...args); + } + + function declareClass(...args) { + return (0, _builder.default)("DeclareClass", ...args); + } + + function declareFunction(...args) { + return (0, _builder.default)("DeclareFunction", ...args); + } + + function declareInterface(...args) { + return (0, _builder.default)("DeclareInterface", ...args); + } + + function declareModule(...args) { + return (0, _builder.default)("DeclareModule", ...args); + } + + function declareModuleExports(...args) { + return (0, _builder.default)("DeclareModuleExports", ...args); + } + + function declareTypeAlias(...args) { + return (0, _builder.default)("DeclareTypeAlias", ...args); + } + + function declareOpaqueType(...args) { + return (0, _builder.default)("DeclareOpaqueType", ...args); + } + + function declareVariable(...args) { + return (0, _builder.default)("DeclareVariable", ...args); + } + + function declareExportDeclaration(...args) { + return (0, _builder.default)("DeclareExportDeclaration", ...args); + } + + function declareExportAllDeclaration(...args) { + return (0, _builder.default)("DeclareExportAllDeclaration", ...args); + } + + function declaredPredicate(...args) { + return (0, _builder.default)("DeclaredPredicate", ...args); + } + + function existsTypeAnnotation(...args) { + return (0, _builder.default)("ExistsTypeAnnotation", ...args); + } + + function functionTypeAnnotation(...args) { + return (0, _builder.default)("FunctionTypeAnnotation", ...args); + } + + function functionTypeParam(...args) { + return (0, _builder.default)("FunctionTypeParam", ...args); + } + + function genericTypeAnnotation(...args) { + return (0, _builder.default)("GenericTypeAnnotation", ...args); + } + + function inferredPredicate(...args) { + return (0, _builder.default)("InferredPredicate", ...args); + } + + function interfaceExtends(...args) { + return (0, _builder.default)("InterfaceExtends", ...args); + } + + function interfaceDeclaration(...args) { + return (0, _builder.default)("InterfaceDeclaration", ...args); + } + + function interfaceTypeAnnotation(...args) { + return (0, _builder.default)("InterfaceTypeAnnotation", ...args); + } + + function intersectionTypeAnnotation(...args) { + return (0, _builder.default)("IntersectionTypeAnnotation", ...args); + } + + function mixedTypeAnnotation(...args) { + return (0, _builder.default)("MixedTypeAnnotation", ...args); + } + + function emptyTypeAnnotation(...args) { + return (0, _builder.default)("EmptyTypeAnnotation", ...args); + } + + function nullableTypeAnnotation(...args) { + return (0, _builder.default)("NullableTypeAnnotation", ...args); + } + + function numberLiteralTypeAnnotation(...args) { + return (0, _builder.default)("NumberLiteralTypeAnnotation", ...args); + } + + function numberTypeAnnotation(...args) { + return (0, _builder.default)("NumberTypeAnnotation", ...args); + } + + function objectTypeAnnotation(...args) { + return (0, _builder.default)("ObjectTypeAnnotation", ...args); + } + + function objectTypeInternalSlot(...args) { + return (0, _builder.default)("ObjectTypeInternalSlot", ...args); + } + + function objectTypeCallProperty(...args) { + return (0, _builder.default)("ObjectTypeCallProperty", ...args); + } + + function objectTypeIndexer(...args) { + return (0, _builder.default)("ObjectTypeIndexer", ...args); + } + + function objectTypeProperty(...args) { + return (0, _builder.default)("ObjectTypeProperty", ...args); + } + + function objectTypeSpreadProperty(...args) { + return (0, _builder.default)("ObjectTypeSpreadProperty", ...args); + } + + function opaqueType(...args) { + return (0, _builder.default)("OpaqueType", ...args); + } + + function qualifiedTypeIdentifier(...args) { + return (0, _builder.default)("QualifiedTypeIdentifier", ...args); + } + + function stringLiteralTypeAnnotation(...args) { + return (0, _builder.default)("StringLiteralTypeAnnotation", ...args); + } + + function stringTypeAnnotation(...args) { + return (0, _builder.default)("StringTypeAnnotation", ...args); + } + + function symbolTypeAnnotation(...args) { + return (0, _builder.default)("SymbolTypeAnnotation", ...args); + } + + function thisTypeAnnotation(...args) { + return (0, _builder.default)("ThisTypeAnnotation", ...args); + } + + function tupleTypeAnnotation(...args) { + return (0, _builder.default)("TupleTypeAnnotation", ...args); + } + + function typeofTypeAnnotation(...args) { + return (0, _builder.default)("TypeofTypeAnnotation", ...args); + } + + function typeAlias(...args) { + return (0, _builder.default)("TypeAlias", ...args); + } + + function typeAnnotation(...args) { + return (0, _builder.default)("TypeAnnotation", ...args); + } + + function typeCastExpression(...args) { + return (0, _builder.default)("TypeCastExpression", ...args); + } + + function typeParameter(...args) { + return (0, _builder.default)("TypeParameter", ...args); + } + + function typeParameterDeclaration(...args) { + return (0, _builder.default)("TypeParameterDeclaration", ...args); + } + + function typeParameterInstantiation(...args) { + return (0, _builder.default)("TypeParameterInstantiation", ...args); + } + + function unionTypeAnnotation(...args) { + return (0, _builder.default)("UnionTypeAnnotation", ...args); + } + + function variance(...args) { + return (0, _builder.default)("Variance", ...args); + } + + function voidTypeAnnotation(...args) { + return (0, _builder.default)("VoidTypeAnnotation", ...args); + } + + function enumDeclaration(...args) { + return (0, _builder.default)("EnumDeclaration", ...args); + } + + function enumBooleanBody(...args) { + return (0, _builder.default)("EnumBooleanBody", ...args); + } + + function enumNumberBody(...args) { + return (0, _builder.default)("EnumNumberBody", ...args); + } + + function enumStringBody(...args) { + return (0, _builder.default)("EnumStringBody", ...args); + } + + function enumSymbolBody(...args) { + return (0, _builder.default)("EnumSymbolBody", ...args); + } + + function enumBooleanMember(...args) { + return (0, _builder.default)("EnumBooleanMember", ...args); + } + + function enumNumberMember(...args) { + return (0, _builder.default)("EnumNumberMember", ...args); + } + + function enumStringMember(...args) { + return (0, _builder.default)("EnumStringMember", ...args); + } + + function enumDefaultedMember(...args) { + return (0, _builder.default)("EnumDefaultedMember", ...args); + } + + function jsxAttribute(...args) { + return (0, _builder.default)("JSXAttribute", ...args); + } + + function jsxClosingElement(...args) { + return (0, _builder.default)("JSXClosingElement", ...args); + } + + function jsxElement(...args) { + return (0, _builder.default)("JSXElement", ...args); + } + + function jsxEmptyExpression(...args) { + return (0, _builder.default)("JSXEmptyExpression", ...args); + } + + function jsxExpressionContainer(...args) { + return (0, _builder.default)("JSXExpressionContainer", ...args); + } + + function jsxSpreadChild(...args) { + return (0, _builder.default)("JSXSpreadChild", ...args); + } + + function jsxIdentifier(...args) { + return (0, _builder.default)("JSXIdentifier", ...args); + } + + function jsxMemberExpression(...args) { + return (0, _builder.default)("JSXMemberExpression", ...args); + } + + function jsxNamespacedName(...args) { + return (0, _builder.default)("JSXNamespacedName", ...args); + } + + function jsxOpeningElement(...args) { + return (0, _builder.default)("JSXOpeningElement", ...args); + } + + function jsxSpreadAttribute(...args) { + return (0, _builder.default)("JSXSpreadAttribute", ...args); + } + + function jsxText(...args) { + return (0, _builder.default)("JSXText", ...args); + } + + function jsxFragment(...args) { + return (0, _builder.default)("JSXFragment", ...args); + } + + function jsxOpeningFragment(...args) { + return (0, _builder.default)("JSXOpeningFragment", ...args); + } + + function jsxClosingFragment(...args) { + return (0, _builder.default)("JSXClosingFragment", ...args); + } + + function noop(...args) { + return (0, _builder.default)("Noop", ...args); + } + + function placeholder(...args) { + return (0, _builder.default)("Placeholder", ...args); + } + + function v8IntrinsicIdentifier(...args) { + return (0, _builder.default)("V8IntrinsicIdentifier", ...args); + } + + function argumentPlaceholder(...args) { + return (0, _builder.default)("ArgumentPlaceholder", ...args); + } + + function bindExpression(...args) { + return (0, _builder.default)("BindExpression", ...args); + } + + function classProperty(...args) { + return (0, _builder.default)("ClassProperty", ...args); + } + + function pipelineTopicExpression(...args) { + return (0, _builder.default)("PipelineTopicExpression", ...args); + } + + function pipelineBareFunction(...args) { + return (0, _builder.default)("PipelineBareFunction", ...args); + } + + function pipelinePrimaryTopicReference(...args) { + return (0, _builder.default)("PipelinePrimaryTopicReference", ...args); + } + + function classPrivateProperty(...args) { + return (0, _builder.default)("ClassPrivateProperty", ...args); + } + + function classPrivateMethod(...args) { + return (0, _builder.default)("ClassPrivateMethod", ...args); + } + + function importAttribute(...args) { + return (0, _builder.default)("ImportAttribute", ...args); + } + + function decorator(...args) { + return (0, _builder.default)("Decorator", ...args); + } + + function doExpression(...args) { + return (0, _builder.default)("DoExpression", ...args); + } + + function exportDefaultSpecifier(...args) { + return (0, _builder.default)("ExportDefaultSpecifier", ...args); + } + + function privateName(...args) { + return (0, _builder.default)("PrivateName", ...args); + } + + function recordExpression(...args) { + return (0, _builder.default)("RecordExpression", ...args); + } + + function tupleExpression(...args) { + return (0, _builder.default)("TupleExpression", ...args); + } + + function decimalLiteral(...args) { + return (0, _builder.default)("DecimalLiteral", ...args); + } + + function staticBlock(...args) { + return (0, _builder.default)("StaticBlock", ...args); + } + + function tsParameterProperty(...args) { + return (0, _builder.default)("TSParameterProperty", ...args); + } + + function tsDeclareFunction(...args) { + return (0, _builder.default)("TSDeclareFunction", ...args); + } + + function tsDeclareMethod(...args) { + return (0, _builder.default)("TSDeclareMethod", ...args); + } + + function tsQualifiedName(...args) { + return (0, _builder.default)("TSQualifiedName", ...args); + } + + function tsCallSignatureDeclaration(...args) { + return (0, _builder.default)("TSCallSignatureDeclaration", ...args); + } + + function tsConstructSignatureDeclaration(...args) { + return (0, _builder.default)("TSConstructSignatureDeclaration", ...args); + } + + function tsPropertySignature(...args) { + return (0, _builder.default)("TSPropertySignature", ...args); + } + + function tsMethodSignature(...args) { + return (0, _builder.default)("TSMethodSignature", ...args); + } + + function tsIndexSignature(...args) { + return (0, _builder.default)("TSIndexSignature", ...args); + } + + function tsAnyKeyword(...args) { + return (0, _builder.default)("TSAnyKeyword", ...args); + } + + function tsBooleanKeyword(...args) { + return (0, _builder.default)("TSBooleanKeyword", ...args); + } + + function tsBigIntKeyword(...args) { + return (0, _builder.default)("TSBigIntKeyword", ...args); + } + + function tsIntrinsicKeyword(...args) { + return (0, _builder.default)("TSIntrinsicKeyword", ...args); + } + + function tsNeverKeyword(...args) { + return (0, _builder.default)("TSNeverKeyword", ...args); + } + + function tsNullKeyword(...args) { + return (0, _builder.default)("TSNullKeyword", ...args); + } + + function tsNumberKeyword(...args) { + return (0, _builder.default)("TSNumberKeyword", ...args); + } + + function tsObjectKeyword(...args) { + return (0, _builder.default)("TSObjectKeyword", ...args); + } + + function tsStringKeyword(...args) { + return (0, _builder.default)("TSStringKeyword", ...args); + } + + function tsSymbolKeyword(...args) { + return (0, _builder.default)("TSSymbolKeyword", ...args); + } + + function tsUndefinedKeyword(...args) { + return (0, _builder.default)("TSUndefinedKeyword", ...args); + } + + function tsUnknownKeyword(...args) { + return (0, _builder.default)("TSUnknownKeyword", ...args); + } + + function tsVoidKeyword(...args) { + return (0, _builder.default)("TSVoidKeyword", ...args); + } + + function tsThisType(...args) { + return (0, _builder.default)("TSThisType", ...args); + } + + function tsFunctionType(...args) { + return (0, _builder.default)("TSFunctionType", ...args); + } + + function tsConstructorType(...args) { + return (0, _builder.default)("TSConstructorType", ...args); + } + + function tsTypeReference(...args) { + return (0, _builder.default)("TSTypeReference", ...args); + } + + function tsTypePredicate(...args) { + return (0, _builder.default)("TSTypePredicate", ...args); + } + + function tsTypeQuery(...args) { + return (0, _builder.default)("TSTypeQuery", ...args); + } + + function tsTypeLiteral(...args) { + return (0, _builder.default)("TSTypeLiteral", ...args); + } + + function tsArrayType(...args) { + return (0, _builder.default)("TSArrayType", ...args); + } + + function tsTupleType(...args) { + return (0, _builder.default)("TSTupleType", ...args); + } + + function tsOptionalType(...args) { + return (0, _builder.default)("TSOptionalType", ...args); + } + + function tsRestType(...args) { + return (0, _builder.default)("TSRestType", ...args); + } + + function tsNamedTupleMember(...args) { + return (0, _builder.default)("TSNamedTupleMember", ...args); + } + + function tsUnionType(...args) { + return (0, _builder.default)("TSUnionType", ...args); + } + + function tsIntersectionType(...args) { + return (0, _builder.default)("TSIntersectionType", ...args); + } + + function tsConditionalType(...args) { + return (0, _builder.default)("TSConditionalType", ...args); + } + + function tsInferType(...args) { + return (0, _builder.default)("TSInferType", ...args); + } + + function tsParenthesizedType(...args) { + return (0, _builder.default)("TSParenthesizedType", ...args); + } + + function tsTypeOperator(...args) { + return (0, _builder.default)("TSTypeOperator", ...args); + } + + function tsIndexedAccessType(...args) { + return (0, _builder.default)("TSIndexedAccessType", ...args); + } + + function tsMappedType(...args) { + return (0, _builder.default)("TSMappedType", ...args); + } + + function tsLiteralType(...args) { + return (0, _builder.default)("TSLiteralType", ...args); + } + + function tsExpressionWithTypeArguments(...args) { + return (0, _builder.default)("TSExpressionWithTypeArguments", ...args); + } + + function tsInterfaceDeclaration(...args) { + return (0, _builder.default)("TSInterfaceDeclaration", ...args); + } + + function tsInterfaceBody(...args) { + return (0, _builder.default)("TSInterfaceBody", ...args); + } + + function tsTypeAliasDeclaration(...args) { + return (0, _builder.default)("TSTypeAliasDeclaration", ...args); + } + + function tsAsExpression(...args) { + return (0, _builder.default)("TSAsExpression", ...args); + } + + function tsTypeAssertion(...args) { + return (0, _builder.default)("TSTypeAssertion", ...args); + } + + function tsEnumDeclaration(...args) { + return (0, _builder.default)("TSEnumDeclaration", ...args); + } + + function tsEnumMember(...args) { + return (0, _builder.default)("TSEnumMember", ...args); + } + + function tsModuleDeclaration(...args) { + return (0, _builder.default)("TSModuleDeclaration", ...args); + } + + function tsModuleBlock(...args) { + return (0, _builder.default)("TSModuleBlock", ...args); + } + + function tsImportType(...args) { + return (0, _builder.default)("TSImportType", ...args); + } + + function tsImportEqualsDeclaration(...args) { + return (0, _builder.default)("TSImportEqualsDeclaration", ...args); + } + + function tsExternalModuleReference(...args) { + return (0, _builder.default)("TSExternalModuleReference", ...args); + } + + function tsNonNullExpression(...args) { + return (0, _builder.default)("TSNonNullExpression", ...args); + } + + function tsExportAssignment(...args) { + return (0, _builder.default)("TSExportAssignment", ...args); + } + + function tsNamespaceExportDeclaration(...args) { + return (0, _builder.default)("TSNamespaceExportDeclaration", ...args); + } + + function tsTypeAnnotation(...args) { + return (0, _builder.default)("TSTypeAnnotation", ...args); + } + + function tsTypeParameterInstantiation(...args) { + return (0, _builder.default)("TSTypeParameterInstantiation", ...args); + } + + function tsTypeParameterDeclaration(...args) { + return (0, _builder.default)("TSTypeParameterDeclaration", ...args); + } + + function tsTypeParameter(...args) { + return (0, _builder.default)("TSTypeParameter", ...args); + } + + function NumberLiteral(...args) { + console.trace("The node type NumberLiteral has been renamed to NumericLiteral"); + return (0, _builder.default)("NumberLiteral", ...args); + } + + function RegexLiteral(...args) { + console.trace("The node type RegexLiteral has been renamed to RegExpLiteral"); + return (0, _builder.default)("RegexLiteral", ...args); + } + + function RestProperty(...args) { + console.trace("The node type RestProperty has been renamed to RestElement"); + return (0, _builder.default)("RestProperty", ...args); + } + + function SpreadProperty(...args) { + console.trace("The node type SpreadProperty has been renamed to SpreadElement"); + return (0, _builder.default)("SpreadProperty", ...args); + } + }); + + unwrapExports(generated$1); + var generated_1$1 = generated$1.ArrayExpression; + var generated_2$1 = generated$1.arrayExpression; + var generated_3$1 = generated$1.AssignmentExpression; + var generated_4$1 = generated$1.assignmentExpression; + var generated_5$1 = generated$1.BinaryExpression; + var generated_6$1 = generated$1.binaryExpression; + var generated_7$1 = generated$1.InterpreterDirective; + var generated_8$1 = generated$1.interpreterDirective; + var generated_9$1 = generated$1.Directive; + var generated_10$1 = generated$1.directive; + var generated_11$1 = generated$1.DirectiveLiteral; + var generated_12$1 = generated$1.directiveLiteral; + var generated_13$1 = generated$1.BlockStatement; + var generated_14$1 = generated$1.blockStatement; + var generated_15$1 = generated$1.BreakStatement; + var generated_16$1 = generated$1.breakStatement; + var generated_17$1 = generated$1.CallExpression; + var generated_18$1 = generated$1.callExpression; + var generated_19$1 = generated$1.CatchClause; + var generated_20$1 = generated$1.catchClause; + var generated_21$1 = generated$1.ConditionalExpression; + var generated_22$1 = generated$1.conditionalExpression; + var generated_23$1 = generated$1.ContinueStatement; + var generated_24$1 = generated$1.continueStatement; + var generated_25$1 = generated$1.DebuggerStatement; + var generated_26$1 = generated$1.debuggerStatement; + var generated_27$1 = generated$1.DoWhileStatement; + var generated_28$1 = generated$1.doWhileStatement; + var generated_29$1 = generated$1.EmptyStatement; + var generated_30$1 = generated$1.emptyStatement; + var generated_31$1 = generated$1.ExpressionStatement; + var generated_32$1 = generated$1.expressionStatement; + var generated_33$1 = generated$1.File; + var generated_34$1 = generated$1.file; + var generated_35$1 = generated$1.ForInStatement; + var generated_36$1 = generated$1.forInStatement; + var generated_37$1 = generated$1.ForStatement; + var generated_38$1 = generated$1.forStatement; + var generated_39$1 = generated$1.FunctionDeclaration; + var generated_40$1 = generated$1.functionDeclaration; + var generated_41$1 = generated$1.FunctionExpression; + var generated_42$1 = generated$1.functionExpression; + var generated_43$1 = generated$1.Identifier; + var generated_44$1 = generated$1.identifier; + var generated_45$1 = generated$1.IfStatement; + var generated_46$1 = generated$1.ifStatement; + var generated_47$1 = generated$1.LabeledStatement; + var generated_48$1 = generated$1.labeledStatement; + var generated_49$1 = generated$1.StringLiteral; + var generated_50$1 = generated$1.stringLiteral; + var generated_51$1 = generated$1.NumericLiteral; + var generated_52$1 = generated$1.numericLiteral; + var generated_53$1 = generated$1.NullLiteral; + var generated_54$1 = generated$1.nullLiteral; + var generated_55$1 = generated$1.BooleanLiteral; + var generated_56$1 = generated$1.booleanLiteral; + var generated_57$1 = generated$1.RegExpLiteral; + var generated_58$1 = generated$1.regExpLiteral; + var generated_59$1 = generated$1.LogicalExpression; + var generated_60$1 = generated$1.logicalExpression; + var generated_61$1 = generated$1.MemberExpression; + var generated_62$1 = generated$1.memberExpression; + var generated_63$1 = generated$1.NewExpression; + var generated_64$1 = generated$1.newExpression; + var generated_65$1 = generated$1.Program; + var generated_66$1 = generated$1.program; + var generated_67$1 = generated$1.ObjectExpression; + var generated_68$1 = generated$1.objectExpression; + var generated_69$1 = generated$1.ObjectMethod; + var generated_70$1 = generated$1.objectMethod; + var generated_71$1 = generated$1.ObjectProperty; + var generated_72$1 = generated$1.objectProperty; + var generated_73$1 = generated$1.RestElement; + var generated_74$1 = generated$1.restElement; + var generated_75$1 = generated$1.ReturnStatement; + var generated_76$1 = generated$1.returnStatement; + var generated_77$1 = generated$1.SequenceExpression; + var generated_78$1 = generated$1.sequenceExpression; + var generated_79$1 = generated$1.ParenthesizedExpression; + var generated_80$1 = generated$1.parenthesizedExpression; + var generated_81$1 = generated$1.SwitchCase; + var generated_82$1 = generated$1.switchCase; + var generated_83$1 = generated$1.SwitchStatement; + var generated_84$1 = generated$1.switchStatement; + var generated_85$1 = generated$1.ThisExpression; + var generated_86$1 = generated$1.thisExpression; + var generated_87$1 = generated$1.ThrowStatement; + var generated_88$1 = generated$1.throwStatement; + var generated_89$1 = generated$1.TryStatement; + var generated_90$1 = generated$1.tryStatement; + var generated_91$1 = generated$1.UnaryExpression; + var generated_92$1 = generated$1.unaryExpression; + var generated_93$1 = generated$1.UpdateExpression; + var generated_94$1 = generated$1.updateExpression; + var generated_95$1 = generated$1.VariableDeclaration; + var generated_96$1 = generated$1.variableDeclaration; + var generated_97$1 = generated$1.VariableDeclarator; + var generated_98$1 = generated$1.variableDeclarator; + var generated_99$1 = generated$1.WhileStatement; + var generated_100$1 = generated$1.whileStatement; + var generated_101$1 = generated$1.WithStatement; + var generated_102$1 = generated$1.withStatement; + var generated_103$1 = generated$1.AssignmentPattern; + var generated_104$1 = generated$1.assignmentPattern; + var generated_105$1 = generated$1.ArrayPattern; + var generated_106$1 = generated$1.arrayPattern; + var generated_107$1 = generated$1.ArrowFunctionExpression; + var generated_108$1 = generated$1.arrowFunctionExpression; + var generated_109$1 = generated$1.ClassBody; + var generated_110$1 = generated$1.classBody; + var generated_111$1 = generated$1.ClassExpression; + var generated_112$1 = generated$1.classExpression; + var generated_113$1 = generated$1.ClassDeclaration; + var generated_114$1 = generated$1.classDeclaration; + var generated_115$1 = generated$1.ExportAllDeclaration; + var generated_116$1 = generated$1.exportAllDeclaration; + var generated_117$1 = generated$1.ExportDefaultDeclaration; + var generated_118$1 = generated$1.exportDefaultDeclaration; + var generated_119$1 = generated$1.ExportNamedDeclaration; + var generated_120$1 = generated$1.exportNamedDeclaration; + var generated_121$1 = generated$1.ExportSpecifier; + var generated_122$1 = generated$1.exportSpecifier; + var generated_123$1 = generated$1.ForOfStatement; + var generated_124$1 = generated$1.forOfStatement; + var generated_125$1 = generated$1.ImportDeclaration; + var generated_126$1 = generated$1.importDeclaration; + var generated_127$1 = generated$1.ImportDefaultSpecifier; + var generated_128$1 = generated$1.importDefaultSpecifier; + var generated_129$1 = generated$1.ImportNamespaceSpecifier; + var generated_130$1 = generated$1.importNamespaceSpecifier; + var generated_131$1 = generated$1.ImportSpecifier; + var generated_132$1 = generated$1.importSpecifier; + var generated_133$1 = generated$1.MetaProperty; + var generated_134$1 = generated$1.metaProperty; + var generated_135$1 = generated$1.ClassMethod; + var generated_136$1 = generated$1.classMethod; + var generated_137$1 = generated$1.ObjectPattern; + var generated_138$1 = generated$1.objectPattern; + var generated_139$1 = generated$1.SpreadElement; + var generated_140$1 = generated$1.spreadElement; + var generated_141$1 = generated$1.Super; + var generated_142$1 = generated$1.TaggedTemplateExpression; + var generated_143$1 = generated$1.taggedTemplateExpression; + var generated_144$1 = generated$1.TemplateElement; + var generated_145$1 = generated$1.templateElement; + var generated_146$1 = generated$1.TemplateLiteral; + var generated_147$1 = generated$1.templateLiteral; + var generated_148$1 = generated$1.YieldExpression; + var generated_149$1 = generated$1.yieldExpression; + var generated_150$1 = generated$1.AwaitExpression; + var generated_151$1 = generated$1.awaitExpression; + var generated_152$1 = generated$1.Import; + var generated_153$1 = generated$1.BigIntLiteral; + var generated_154$1 = generated$1.bigIntLiteral; + var generated_155$1 = generated$1.ExportNamespaceSpecifier; + var generated_156$1 = generated$1.exportNamespaceSpecifier; + var generated_157$1 = generated$1.OptionalMemberExpression; + var generated_158$1 = generated$1.optionalMemberExpression; + var generated_159$1 = generated$1.OptionalCallExpression; + var generated_160$1 = generated$1.optionalCallExpression; + var generated_161$1 = generated$1.AnyTypeAnnotation; + var generated_162$1 = generated$1.anyTypeAnnotation; + var generated_163$1 = generated$1.ArrayTypeAnnotation; + var generated_164$1 = generated$1.arrayTypeAnnotation; + var generated_165$1 = generated$1.BooleanTypeAnnotation; + var generated_166$1 = generated$1.booleanTypeAnnotation; + var generated_167$1 = generated$1.BooleanLiteralTypeAnnotation; + var generated_168$1 = generated$1.booleanLiteralTypeAnnotation; + var generated_169$1 = generated$1.NullLiteralTypeAnnotation; + var generated_170$1 = generated$1.nullLiteralTypeAnnotation; + var generated_171$1 = generated$1.ClassImplements; + var generated_172$1 = generated$1.classImplements; + var generated_173$1 = generated$1.DeclareClass; + var generated_174$1 = generated$1.declareClass; + var generated_175$1 = generated$1.DeclareFunction; + var generated_176$1 = generated$1.declareFunction; + var generated_177$1 = generated$1.DeclareInterface; + var generated_178$1 = generated$1.declareInterface; + var generated_179$1 = generated$1.DeclareModule; + var generated_180$1 = generated$1.declareModule; + var generated_181$1 = generated$1.DeclareModuleExports; + var generated_182$1 = generated$1.declareModuleExports; + var generated_183$1 = generated$1.DeclareTypeAlias; + var generated_184$1 = generated$1.declareTypeAlias; + var generated_185$1 = generated$1.DeclareOpaqueType; + var generated_186$1 = generated$1.declareOpaqueType; + var generated_187$1 = generated$1.DeclareVariable; + var generated_188$1 = generated$1.declareVariable; + var generated_189$1 = generated$1.DeclareExportDeclaration; + var generated_190$1 = generated$1.declareExportDeclaration; + var generated_191$1 = generated$1.DeclareExportAllDeclaration; + var generated_192$1 = generated$1.declareExportAllDeclaration; + var generated_193$1 = generated$1.DeclaredPredicate; + var generated_194$1 = generated$1.declaredPredicate; + var generated_195$1 = generated$1.ExistsTypeAnnotation; + var generated_196$1 = generated$1.existsTypeAnnotation; + var generated_197$1 = generated$1.FunctionTypeAnnotation; + var generated_198$1 = generated$1.functionTypeAnnotation; + var generated_199$1 = generated$1.FunctionTypeParam; + var generated_200$1 = generated$1.functionTypeParam; + var generated_201$1 = generated$1.GenericTypeAnnotation; + var generated_202$1 = generated$1.genericTypeAnnotation; + var generated_203$1 = generated$1.InferredPredicate; + var generated_204$1 = generated$1.inferredPredicate; + var generated_205$1 = generated$1.InterfaceExtends; + var generated_206$1 = generated$1.interfaceExtends; + var generated_207$1 = generated$1.InterfaceDeclaration; + var generated_208$1 = generated$1.interfaceDeclaration; + var generated_209$1 = generated$1.InterfaceTypeAnnotation; + var generated_210$1 = generated$1.interfaceTypeAnnotation; + var generated_211$1 = generated$1.IntersectionTypeAnnotation; + var generated_212$1 = generated$1.intersectionTypeAnnotation; + var generated_213$1 = generated$1.MixedTypeAnnotation; + var generated_214$1 = generated$1.mixedTypeAnnotation; + var generated_215$1 = generated$1.EmptyTypeAnnotation; + var generated_216$1 = generated$1.emptyTypeAnnotation; + var generated_217$1 = generated$1.NullableTypeAnnotation; + var generated_218$1 = generated$1.nullableTypeAnnotation; + var generated_219$1 = generated$1.NumberLiteralTypeAnnotation; + var generated_220$1 = generated$1.numberLiteralTypeAnnotation; + var generated_221$1 = generated$1.NumberTypeAnnotation; + var generated_222$1 = generated$1.numberTypeAnnotation; + var generated_223$1 = generated$1.ObjectTypeAnnotation; + var generated_224$1 = generated$1.objectTypeAnnotation; + var generated_225$1 = generated$1.ObjectTypeInternalSlot; + var generated_226$1 = generated$1.objectTypeInternalSlot; + var generated_227$1 = generated$1.ObjectTypeCallProperty; + var generated_228$1 = generated$1.objectTypeCallProperty; + var generated_229$1 = generated$1.ObjectTypeIndexer; + var generated_230$1 = generated$1.objectTypeIndexer; + var generated_231$1 = generated$1.ObjectTypeProperty; + var generated_232$1 = generated$1.objectTypeProperty; + var generated_233$1 = generated$1.ObjectTypeSpreadProperty; + var generated_234$1 = generated$1.objectTypeSpreadProperty; + var generated_235$1 = generated$1.OpaqueType; + var generated_236$1 = generated$1.opaqueType; + var generated_237$1 = generated$1.QualifiedTypeIdentifier; + var generated_238$1 = generated$1.qualifiedTypeIdentifier; + var generated_239$1 = generated$1.StringLiteralTypeAnnotation; + var generated_240$1 = generated$1.stringLiteralTypeAnnotation; + var generated_241$1 = generated$1.StringTypeAnnotation; + var generated_242$1 = generated$1.stringTypeAnnotation; + var generated_243$1 = generated$1.SymbolTypeAnnotation; + var generated_244$1 = generated$1.symbolTypeAnnotation; + var generated_245$1 = generated$1.ThisTypeAnnotation; + var generated_246$1 = generated$1.thisTypeAnnotation; + var generated_247$1 = generated$1.TupleTypeAnnotation; + var generated_248$1 = generated$1.tupleTypeAnnotation; + var generated_249$1 = generated$1.TypeofTypeAnnotation; + var generated_250$1 = generated$1.typeofTypeAnnotation; + var generated_251$1 = generated$1.TypeAlias; + var generated_252$1 = generated$1.typeAlias; + var generated_253$1 = generated$1.TypeAnnotation; + var generated_254$1 = generated$1.typeAnnotation; + var generated_255$1 = generated$1.TypeCastExpression; + var generated_256$1 = generated$1.typeCastExpression; + var generated_257$1 = generated$1.TypeParameter; + var generated_258$1 = generated$1.typeParameter; + var generated_259$1 = generated$1.TypeParameterDeclaration; + var generated_260$1 = generated$1.typeParameterDeclaration; + var generated_261$1 = generated$1.TypeParameterInstantiation; + var generated_262$1 = generated$1.typeParameterInstantiation; + var generated_263$1 = generated$1.UnionTypeAnnotation; + var generated_264$1 = generated$1.unionTypeAnnotation; + var generated_265$1 = generated$1.Variance; + var generated_266$1 = generated$1.variance; + var generated_267$1 = generated$1.VoidTypeAnnotation; + var generated_268$1 = generated$1.voidTypeAnnotation; + var generated_269$1 = generated$1.EnumDeclaration; + var generated_270$1 = generated$1.enumDeclaration; + var generated_271$1 = generated$1.EnumBooleanBody; + var generated_272$1 = generated$1.enumBooleanBody; + var generated_273$1 = generated$1.EnumNumberBody; + var generated_274$1 = generated$1.enumNumberBody; + var generated_275$1 = generated$1.EnumStringBody; + var generated_276$1 = generated$1.enumStringBody; + var generated_277$1 = generated$1.EnumSymbolBody; + var generated_278$1 = generated$1.enumSymbolBody; + var generated_279$1 = generated$1.EnumBooleanMember; + var generated_280$1 = generated$1.enumBooleanMember; + var generated_281$1 = generated$1.EnumNumberMember; + var generated_282$1 = generated$1.enumNumberMember; + var generated_283$1 = generated$1.EnumStringMember; + var generated_284$1 = generated$1.enumStringMember; + var generated_285$1 = generated$1.EnumDefaultedMember; + var generated_286$1 = generated$1.enumDefaultedMember; + var generated_287$1 = generated$1.jSXAttribute; + var generated_288$1 = generated$1.JSXAttribute; + var generated_289$1 = generated$1.jsxAttribute; + var generated_290$1 = generated$1.jSXClosingElement; + var generated_291$1 = generated$1.JSXClosingElement; + var generated_292 = generated$1.jsxClosingElement; + var generated_293 = generated$1.jSXElement; + var generated_294 = generated$1.JSXElement; + var generated_295 = generated$1.jsxElement; + var generated_296 = generated$1.jSXEmptyExpression; + var generated_297 = generated$1.JSXEmptyExpression; + var generated_298 = generated$1.jsxEmptyExpression; + var generated_299 = generated$1.jSXExpressionContainer; + var generated_300 = generated$1.JSXExpressionContainer; + var generated_301 = generated$1.jsxExpressionContainer; + var generated_302 = generated$1.jSXSpreadChild; + var generated_303 = generated$1.JSXSpreadChild; + var generated_304 = generated$1.jsxSpreadChild; + var generated_305 = generated$1.jSXIdentifier; + var generated_306 = generated$1.JSXIdentifier; + var generated_307 = generated$1.jsxIdentifier; + var generated_308 = generated$1.jSXMemberExpression; + var generated_309 = generated$1.JSXMemberExpression; + var generated_310 = generated$1.jsxMemberExpression; + var generated_311 = generated$1.jSXNamespacedName; + var generated_312 = generated$1.JSXNamespacedName; + var generated_313 = generated$1.jsxNamespacedName; + var generated_314 = generated$1.jSXOpeningElement; + var generated_315 = generated$1.JSXOpeningElement; + var generated_316 = generated$1.jsxOpeningElement; + var generated_317 = generated$1.jSXSpreadAttribute; + var generated_318 = generated$1.JSXSpreadAttribute; + var generated_319 = generated$1.jsxSpreadAttribute; + var generated_320 = generated$1.jSXText; + var generated_321 = generated$1.JSXText; + var generated_322 = generated$1.jsxText; + var generated_323 = generated$1.jSXFragment; + var generated_324 = generated$1.JSXFragment; + var generated_325 = generated$1.jsxFragment; + var generated_326 = generated$1.jSXOpeningFragment; + var generated_327 = generated$1.JSXOpeningFragment; + var generated_328 = generated$1.jsxOpeningFragment; + var generated_329 = generated$1.jSXClosingFragment; + var generated_330 = generated$1.JSXClosingFragment; + var generated_331 = generated$1.jsxClosingFragment; + var generated_332 = generated$1.Noop; + var generated_333 = generated$1.noop; + var generated_334 = generated$1.Placeholder; + var generated_335 = generated$1.placeholder; + var generated_336 = generated$1.V8IntrinsicIdentifier; + var generated_337 = generated$1.v8IntrinsicIdentifier; + var generated_338 = generated$1.ArgumentPlaceholder; + var generated_339 = generated$1.argumentPlaceholder; + var generated_340 = generated$1.BindExpression; + var generated_341 = generated$1.bindExpression; + var generated_342 = generated$1.ClassProperty; + var generated_343 = generated$1.classProperty; + var generated_344 = generated$1.PipelineTopicExpression; + var generated_345 = generated$1.pipelineTopicExpression; + var generated_346 = generated$1.PipelineBareFunction; + var generated_347 = generated$1.pipelineBareFunction; + var generated_348 = generated$1.PipelinePrimaryTopicReference; + var generated_349 = generated$1.pipelinePrimaryTopicReference; + var generated_350 = generated$1.ClassPrivateProperty; + var generated_351 = generated$1.classPrivateProperty; + var generated_352 = generated$1.ClassPrivateMethod; + var generated_353 = generated$1.classPrivateMethod; + var generated_354 = generated$1.ImportAttribute; + var generated_355 = generated$1.importAttribute; + var generated_356 = generated$1.Decorator; + var generated_357 = generated$1.decorator; + var generated_358 = generated$1.DoExpression; + var generated_359 = generated$1.doExpression; + var generated_360 = generated$1.ExportDefaultSpecifier; + var generated_361 = generated$1.exportDefaultSpecifier; + var generated_362 = generated$1.PrivateName; + var generated_363 = generated$1.privateName; + var generated_364 = generated$1.RecordExpression; + var generated_365 = generated$1.recordExpression; + var generated_366 = generated$1.TupleExpression; + var generated_367 = generated$1.tupleExpression; + var generated_368 = generated$1.DecimalLiteral; + var generated_369 = generated$1.decimalLiteral; + var generated_370 = generated$1.StaticBlock; + var generated_371 = generated$1.staticBlock; + var generated_372 = generated$1.tSParameterProperty; + var generated_373 = generated$1.TSParameterProperty; + var generated_374 = generated$1.tsParameterProperty; + var generated_375 = generated$1.tSDeclareFunction; + var generated_376 = generated$1.TSDeclareFunction; + var generated_377 = generated$1.tsDeclareFunction; + var generated_378 = generated$1.tSDeclareMethod; + var generated_379 = generated$1.TSDeclareMethod; + var generated_380 = generated$1.tsDeclareMethod; + var generated_381 = generated$1.tSQualifiedName; + var generated_382 = generated$1.TSQualifiedName; + var generated_383 = generated$1.tsQualifiedName; + var generated_384 = generated$1.tSCallSignatureDeclaration; + var generated_385 = generated$1.TSCallSignatureDeclaration; + var generated_386 = generated$1.tsCallSignatureDeclaration; + var generated_387 = generated$1.tSConstructSignatureDeclaration; + var generated_388 = generated$1.TSConstructSignatureDeclaration; + var generated_389 = generated$1.tsConstructSignatureDeclaration; + var generated_390 = generated$1.tSPropertySignature; + var generated_391 = generated$1.TSPropertySignature; + var generated_392 = generated$1.tsPropertySignature; + var generated_393 = generated$1.tSMethodSignature; + var generated_394 = generated$1.TSMethodSignature; + var generated_395 = generated$1.tsMethodSignature; + var generated_396 = generated$1.tSIndexSignature; + var generated_397 = generated$1.TSIndexSignature; + var generated_398 = generated$1.tsIndexSignature; + var generated_399 = generated$1.tSAnyKeyword; + var generated_400 = generated$1.TSAnyKeyword; + var generated_401 = generated$1.tsAnyKeyword; + var generated_402 = generated$1.tSBooleanKeyword; + var generated_403 = generated$1.TSBooleanKeyword; + var generated_404 = generated$1.tsBooleanKeyword; + var generated_405 = generated$1.tSBigIntKeyword; + var generated_406 = generated$1.TSBigIntKeyword; + var generated_407 = generated$1.tsBigIntKeyword; + var generated_408 = generated$1.tSIntrinsicKeyword; + var generated_409 = generated$1.TSIntrinsicKeyword; + var generated_410 = generated$1.tsIntrinsicKeyword; + var generated_411 = generated$1.tSNeverKeyword; + var generated_412 = generated$1.TSNeverKeyword; + var generated_413 = generated$1.tsNeverKeyword; + var generated_414 = generated$1.tSNullKeyword; + var generated_415 = generated$1.TSNullKeyword; + var generated_416 = generated$1.tsNullKeyword; + var generated_417 = generated$1.tSNumberKeyword; + var generated_418 = generated$1.TSNumberKeyword; + var generated_419 = generated$1.tsNumberKeyword; + var generated_420 = generated$1.tSObjectKeyword; + var generated_421 = generated$1.TSObjectKeyword; + var generated_422 = generated$1.tsObjectKeyword; + var generated_423 = generated$1.tSStringKeyword; + var generated_424 = generated$1.TSStringKeyword; + var generated_425 = generated$1.tsStringKeyword; + var generated_426 = generated$1.tSSymbolKeyword; + var generated_427 = generated$1.TSSymbolKeyword; + var generated_428 = generated$1.tsSymbolKeyword; + var generated_429 = generated$1.tSUndefinedKeyword; + var generated_430 = generated$1.TSUndefinedKeyword; + var generated_431 = generated$1.tsUndefinedKeyword; + var generated_432 = generated$1.tSUnknownKeyword; + var generated_433 = generated$1.TSUnknownKeyword; + var generated_434 = generated$1.tsUnknownKeyword; + var generated_435 = generated$1.tSVoidKeyword; + var generated_436 = generated$1.TSVoidKeyword; + var generated_437 = generated$1.tsVoidKeyword; + var generated_438 = generated$1.tSThisType; + var generated_439 = generated$1.TSThisType; + var generated_440 = generated$1.tsThisType; + var generated_441 = generated$1.tSFunctionType; + var generated_442 = generated$1.TSFunctionType; + var generated_443 = generated$1.tsFunctionType; + var generated_444 = generated$1.tSConstructorType; + var generated_445 = generated$1.TSConstructorType; + var generated_446 = generated$1.tsConstructorType; + var generated_447 = generated$1.tSTypeReference; + var generated_448 = generated$1.TSTypeReference; + var generated_449 = generated$1.tsTypeReference; + var generated_450 = generated$1.tSTypePredicate; + var generated_451 = generated$1.TSTypePredicate; + var generated_452 = generated$1.tsTypePredicate; + var generated_453 = generated$1.tSTypeQuery; + var generated_454 = generated$1.TSTypeQuery; + var generated_455 = generated$1.tsTypeQuery; + var generated_456 = generated$1.tSTypeLiteral; + var generated_457 = generated$1.TSTypeLiteral; + var generated_458 = generated$1.tsTypeLiteral; + var generated_459 = generated$1.tSArrayType; + var generated_460 = generated$1.TSArrayType; + var generated_461 = generated$1.tsArrayType; + var generated_462 = generated$1.tSTupleType; + var generated_463 = generated$1.TSTupleType; + var generated_464 = generated$1.tsTupleType; + var generated_465 = generated$1.tSOptionalType; + var generated_466 = generated$1.TSOptionalType; + var generated_467 = generated$1.tsOptionalType; + var generated_468 = generated$1.tSRestType; + var generated_469 = generated$1.TSRestType; + var generated_470 = generated$1.tsRestType; + var generated_471 = generated$1.tSNamedTupleMember; + var generated_472 = generated$1.TSNamedTupleMember; + var generated_473 = generated$1.tsNamedTupleMember; + var generated_474 = generated$1.tSUnionType; + var generated_475 = generated$1.TSUnionType; + var generated_476 = generated$1.tsUnionType; + var generated_477 = generated$1.tSIntersectionType; + var generated_478 = generated$1.TSIntersectionType; + var generated_479 = generated$1.tsIntersectionType; + var generated_480 = generated$1.tSConditionalType; + var generated_481 = generated$1.TSConditionalType; + var generated_482 = generated$1.tsConditionalType; + var generated_483 = generated$1.tSInferType; + var generated_484 = generated$1.TSInferType; + var generated_485 = generated$1.tsInferType; + var generated_486 = generated$1.tSParenthesizedType; + var generated_487 = generated$1.TSParenthesizedType; + var generated_488 = generated$1.tsParenthesizedType; + var generated_489 = generated$1.tSTypeOperator; + var generated_490 = generated$1.TSTypeOperator; + var generated_491 = generated$1.tsTypeOperator; + var generated_492 = generated$1.tSIndexedAccessType; + var generated_493 = generated$1.TSIndexedAccessType; + var generated_494 = generated$1.tsIndexedAccessType; + var generated_495 = generated$1.tSMappedType; + var generated_496 = generated$1.TSMappedType; + var generated_497 = generated$1.tsMappedType; + var generated_498 = generated$1.tSLiteralType; + var generated_499 = generated$1.TSLiteralType; + var generated_500 = generated$1.tsLiteralType; + var generated_501 = generated$1.tSExpressionWithTypeArguments; + var generated_502 = generated$1.TSExpressionWithTypeArguments; + var generated_503 = generated$1.tsExpressionWithTypeArguments; + var generated_504 = generated$1.tSInterfaceDeclaration; + var generated_505 = generated$1.TSInterfaceDeclaration; + var generated_506 = generated$1.tsInterfaceDeclaration; + var generated_507 = generated$1.tSInterfaceBody; + var generated_508 = generated$1.TSInterfaceBody; + var generated_509 = generated$1.tsInterfaceBody; + var generated_510 = generated$1.tSTypeAliasDeclaration; + var generated_511 = generated$1.TSTypeAliasDeclaration; + var generated_512 = generated$1.tsTypeAliasDeclaration; + var generated_513 = generated$1.tSAsExpression; + var generated_514 = generated$1.TSAsExpression; + var generated_515 = generated$1.tsAsExpression; + var generated_516 = generated$1.tSTypeAssertion; + var generated_517 = generated$1.TSTypeAssertion; + var generated_518 = generated$1.tsTypeAssertion; + var generated_519 = generated$1.tSEnumDeclaration; + var generated_520 = generated$1.TSEnumDeclaration; + var generated_521 = generated$1.tsEnumDeclaration; + var generated_522 = generated$1.tSEnumMember; + var generated_523 = generated$1.TSEnumMember; + var generated_524 = generated$1.tsEnumMember; + var generated_525 = generated$1.tSModuleDeclaration; + var generated_526 = generated$1.TSModuleDeclaration; + var generated_527 = generated$1.tsModuleDeclaration; + var generated_528 = generated$1.tSModuleBlock; + var generated_529 = generated$1.TSModuleBlock; + var generated_530 = generated$1.tsModuleBlock; + var generated_531 = generated$1.tSImportType; + var generated_532 = generated$1.TSImportType; + var generated_533 = generated$1.tsImportType; + var generated_534 = generated$1.tSImportEqualsDeclaration; + var generated_535 = generated$1.TSImportEqualsDeclaration; + var generated_536 = generated$1.tsImportEqualsDeclaration; + var generated_537 = generated$1.tSExternalModuleReference; + var generated_538 = generated$1.TSExternalModuleReference; + var generated_539 = generated$1.tsExternalModuleReference; + var generated_540 = generated$1.tSNonNullExpression; + var generated_541 = generated$1.TSNonNullExpression; + var generated_542 = generated$1.tsNonNullExpression; + var generated_543 = generated$1.tSExportAssignment; + var generated_544 = generated$1.TSExportAssignment; + var generated_545 = generated$1.tsExportAssignment; + var generated_546 = generated$1.tSNamespaceExportDeclaration; + var generated_547 = generated$1.TSNamespaceExportDeclaration; + var generated_548 = generated$1.tsNamespaceExportDeclaration; + var generated_549 = generated$1.tSTypeAnnotation; + var generated_550 = generated$1.TSTypeAnnotation; + var generated_551 = generated$1.tsTypeAnnotation; + var generated_552 = generated$1.tSTypeParameterInstantiation; + var generated_553 = generated$1.TSTypeParameterInstantiation; + var generated_554 = generated$1.tsTypeParameterInstantiation; + var generated_555 = generated$1.tSTypeParameterDeclaration; + var generated_556 = generated$1.TSTypeParameterDeclaration; + var generated_557 = generated$1.tsTypeParameterDeclaration; + var generated_558 = generated$1.tSTypeParameter; + var generated_559 = generated$1.TSTypeParameter; + var generated_560 = generated$1.tsTypeParameter; + var generated_561 = generated$1.numberLiteral; + var generated_562 = generated$1.NumberLiteral; + var generated_563 = generated$1.regexLiteral; + var generated_564 = generated$1.RegexLiteral; + var generated_565 = generated$1.restProperty; + var generated_566 = generated$1.RestProperty; + var generated_567 = generated$1.spreadProperty; + var generated_568 = generated$1.SpreadProperty; + + var cleanJSXElementLiteralChild_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = cleanJSXElementLiteralChild; + + + + function cleanJSXElementLiteralChild(child, args) { + const lines = child.value.split(/\r\n|\n|\r/); + let lastNonEmptyLine = 0; + + for (let i = 0; i < lines.length; i++) { + if (lines[i].match(/[^ \t]/)) { + lastNonEmptyLine = i; + } + } + + let str = ""; + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + const isFirstLine = i === 0; + const isLastLine = i === lines.length - 1; + const isLastNonEmptyLine = i === lastNonEmptyLine; + let trimmedLine = line.replace(/\t/g, " "); + + if (!isFirstLine) { + trimmedLine = trimmedLine.replace(/^[ ]+/, ""); + } + + if (!isLastLine) { + trimmedLine = trimmedLine.replace(/[ ]+$/, ""); + } + + if (trimmedLine) { + if (!isLastNonEmptyLine) { + trimmedLine += " "; + } + + str += trimmedLine; + } + } + + if (str) args.push((0, generated$1.stringLiteral)(str)); + } + }); + + unwrapExports(cleanJSXElementLiteralChild_1); + + var buildChildren_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = buildChildren; + + + + var _cleanJSXElementLiteralChild = _interopRequireDefault(cleanJSXElementLiteralChild_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function buildChildren(node) { + const elements = []; + + for (let i = 0; i < node.children.length; i++) { + let child = node.children[i]; + + if ((0, generated.isJSXText)(child)) { + (0, _cleanJSXElementLiteralChild.default)(child, elements); + continue; + } + + if ((0, generated.isJSXExpressionContainer)(child)) child = child.expression; + if ((0, generated.isJSXEmptyExpression)(child)) continue; + elements.push(child); + } + + return elements; + } + }); + + unwrapExports(buildChildren_1); + + var isNode_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = isNode; + + + + function isNode(node) { + return !!(node && definitions.VISITOR_KEYS[node.type]); + } + }); + + unwrapExports(isNode_1); + + var assertNode_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = assertNode; + + var _isNode = _interopRequireDefault(isNode_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function assertNode(node) { + if (!(0, _isNode.default)(node)) { + var _node$type; + + const type = (_node$type = node == null ? void 0 : node.type) != null ? _node$type : JSON.stringify(node); + throw new TypeError(`Not a valid node of type "${type}"`); + } + } + }); + + unwrapExports(assertNode_1); + + var generated$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.assertArrayExpression = assertArrayExpression; + exports.assertAssignmentExpression = assertAssignmentExpression; + exports.assertBinaryExpression = assertBinaryExpression; + exports.assertInterpreterDirective = assertInterpreterDirective; + exports.assertDirective = assertDirective; + exports.assertDirectiveLiteral = assertDirectiveLiteral; + exports.assertBlockStatement = assertBlockStatement; + exports.assertBreakStatement = assertBreakStatement; + exports.assertCallExpression = assertCallExpression; + exports.assertCatchClause = assertCatchClause; + exports.assertConditionalExpression = assertConditionalExpression; + exports.assertContinueStatement = assertContinueStatement; + exports.assertDebuggerStatement = assertDebuggerStatement; + exports.assertDoWhileStatement = assertDoWhileStatement; + exports.assertEmptyStatement = assertEmptyStatement; + exports.assertExpressionStatement = assertExpressionStatement; + exports.assertFile = assertFile; + exports.assertForInStatement = assertForInStatement; + exports.assertForStatement = assertForStatement; + exports.assertFunctionDeclaration = assertFunctionDeclaration; + exports.assertFunctionExpression = assertFunctionExpression; + exports.assertIdentifier = assertIdentifier; + exports.assertIfStatement = assertIfStatement; + exports.assertLabeledStatement = assertLabeledStatement; + exports.assertStringLiteral = assertStringLiteral; + exports.assertNumericLiteral = assertNumericLiteral; + exports.assertNullLiteral = assertNullLiteral; + exports.assertBooleanLiteral = assertBooleanLiteral; + exports.assertRegExpLiteral = assertRegExpLiteral; + exports.assertLogicalExpression = assertLogicalExpression; + exports.assertMemberExpression = assertMemberExpression; + exports.assertNewExpression = assertNewExpression; + exports.assertProgram = assertProgram; + exports.assertObjectExpression = assertObjectExpression; + exports.assertObjectMethod = assertObjectMethod; + exports.assertObjectProperty = assertObjectProperty; + exports.assertRestElement = assertRestElement; + exports.assertReturnStatement = assertReturnStatement; + exports.assertSequenceExpression = assertSequenceExpression; + exports.assertParenthesizedExpression = assertParenthesizedExpression; + exports.assertSwitchCase = assertSwitchCase; + exports.assertSwitchStatement = assertSwitchStatement; + exports.assertThisExpression = assertThisExpression; + exports.assertThrowStatement = assertThrowStatement; + exports.assertTryStatement = assertTryStatement; + exports.assertUnaryExpression = assertUnaryExpression; + exports.assertUpdateExpression = assertUpdateExpression; + exports.assertVariableDeclaration = assertVariableDeclaration; + exports.assertVariableDeclarator = assertVariableDeclarator; + exports.assertWhileStatement = assertWhileStatement; + exports.assertWithStatement = assertWithStatement; + exports.assertAssignmentPattern = assertAssignmentPattern; + exports.assertArrayPattern = assertArrayPattern; + exports.assertArrowFunctionExpression = assertArrowFunctionExpression; + exports.assertClassBody = assertClassBody; + exports.assertClassExpression = assertClassExpression; + exports.assertClassDeclaration = assertClassDeclaration; + exports.assertExportAllDeclaration = assertExportAllDeclaration; + exports.assertExportDefaultDeclaration = assertExportDefaultDeclaration; + exports.assertExportNamedDeclaration = assertExportNamedDeclaration; + exports.assertExportSpecifier = assertExportSpecifier; + exports.assertForOfStatement = assertForOfStatement; + exports.assertImportDeclaration = assertImportDeclaration; + exports.assertImportDefaultSpecifier = assertImportDefaultSpecifier; + exports.assertImportNamespaceSpecifier = assertImportNamespaceSpecifier; + exports.assertImportSpecifier = assertImportSpecifier; + exports.assertMetaProperty = assertMetaProperty; + exports.assertClassMethod = assertClassMethod; + exports.assertObjectPattern = assertObjectPattern; + exports.assertSpreadElement = assertSpreadElement; + exports.assertSuper = assertSuper; + exports.assertTaggedTemplateExpression = assertTaggedTemplateExpression; + exports.assertTemplateElement = assertTemplateElement; + exports.assertTemplateLiteral = assertTemplateLiteral; + exports.assertYieldExpression = assertYieldExpression; + exports.assertAwaitExpression = assertAwaitExpression; + exports.assertImport = assertImport; + exports.assertBigIntLiteral = assertBigIntLiteral; + exports.assertExportNamespaceSpecifier = assertExportNamespaceSpecifier; + exports.assertOptionalMemberExpression = assertOptionalMemberExpression; + exports.assertOptionalCallExpression = assertOptionalCallExpression; + exports.assertAnyTypeAnnotation = assertAnyTypeAnnotation; + exports.assertArrayTypeAnnotation = assertArrayTypeAnnotation; + exports.assertBooleanTypeAnnotation = assertBooleanTypeAnnotation; + exports.assertBooleanLiteralTypeAnnotation = assertBooleanLiteralTypeAnnotation; + exports.assertNullLiteralTypeAnnotation = assertNullLiteralTypeAnnotation; + exports.assertClassImplements = assertClassImplements; + exports.assertDeclareClass = assertDeclareClass; + exports.assertDeclareFunction = assertDeclareFunction; + exports.assertDeclareInterface = assertDeclareInterface; + exports.assertDeclareModule = assertDeclareModule; + exports.assertDeclareModuleExports = assertDeclareModuleExports; + exports.assertDeclareTypeAlias = assertDeclareTypeAlias; + exports.assertDeclareOpaqueType = assertDeclareOpaqueType; + exports.assertDeclareVariable = assertDeclareVariable; + exports.assertDeclareExportDeclaration = assertDeclareExportDeclaration; + exports.assertDeclareExportAllDeclaration = assertDeclareExportAllDeclaration; + exports.assertDeclaredPredicate = assertDeclaredPredicate; + exports.assertExistsTypeAnnotation = assertExistsTypeAnnotation; + exports.assertFunctionTypeAnnotation = assertFunctionTypeAnnotation; + exports.assertFunctionTypeParam = assertFunctionTypeParam; + exports.assertGenericTypeAnnotation = assertGenericTypeAnnotation; + exports.assertInferredPredicate = assertInferredPredicate; + exports.assertInterfaceExtends = assertInterfaceExtends; + exports.assertInterfaceDeclaration = assertInterfaceDeclaration; + exports.assertInterfaceTypeAnnotation = assertInterfaceTypeAnnotation; + exports.assertIntersectionTypeAnnotation = assertIntersectionTypeAnnotation; + exports.assertMixedTypeAnnotation = assertMixedTypeAnnotation; + exports.assertEmptyTypeAnnotation = assertEmptyTypeAnnotation; + exports.assertNullableTypeAnnotation = assertNullableTypeAnnotation; + exports.assertNumberLiteralTypeAnnotation = assertNumberLiteralTypeAnnotation; + exports.assertNumberTypeAnnotation = assertNumberTypeAnnotation; + exports.assertObjectTypeAnnotation = assertObjectTypeAnnotation; + exports.assertObjectTypeInternalSlot = assertObjectTypeInternalSlot; + exports.assertObjectTypeCallProperty = assertObjectTypeCallProperty; + exports.assertObjectTypeIndexer = assertObjectTypeIndexer; + exports.assertObjectTypeProperty = assertObjectTypeProperty; + exports.assertObjectTypeSpreadProperty = assertObjectTypeSpreadProperty; + exports.assertOpaqueType = assertOpaqueType; + exports.assertQualifiedTypeIdentifier = assertQualifiedTypeIdentifier; + exports.assertStringLiteralTypeAnnotation = assertStringLiteralTypeAnnotation; + exports.assertStringTypeAnnotation = assertStringTypeAnnotation; + exports.assertSymbolTypeAnnotation = assertSymbolTypeAnnotation; + exports.assertThisTypeAnnotation = assertThisTypeAnnotation; + exports.assertTupleTypeAnnotation = assertTupleTypeAnnotation; + exports.assertTypeofTypeAnnotation = assertTypeofTypeAnnotation; + exports.assertTypeAlias = assertTypeAlias; + exports.assertTypeAnnotation = assertTypeAnnotation; + exports.assertTypeCastExpression = assertTypeCastExpression; + exports.assertTypeParameter = assertTypeParameter; + exports.assertTypeParameterDeclaration = assertTypeParameterDeclaration; + exports.assertTypeParameterInstantiation = assertTypeParameterInstantiation; + exports.assertUnionTypeAnnotation = assertUnionTypeAnnotation; + exports.assertVariance = assertVariance; + exports.assertVoidTypeAnnotation = assertVoidTypeAnnotation; + exports.assertEnumDeclaration = assertEnumDeclaration; + exports.assertEnumBooleanBody = assertEnumBooleanBody; + exports.assertEnumNumberBody = assertEnumNumberBody; + exports.assertEnumStringBody = assertEnumStringBody; + exports.assertEnumSymbolBody = assertEnumSymbolBody; + exports.assertEnumBooleanMember = assertEnumBooleanMember; + exports.assertEnumNumberMember = assertEnumNumberMember; + exports.assertEnumStringMember = assertEnumStringMember; + exports.assertEnumDefaultedMember = assertEnumDefaultedMember; + exports.assertJSXAttribute = assertJSXAttribute; + exports.assertJSXClosingElement = assertJSXClosingElement; + exports.assertJSXElement = assertJSXElement; + exports.assertJSXEmptyExpression = assertJSXEmptyExpression; + exports.assertJSXExpressionContainer = assertJSXExpressionContainer; + exports.assertJSXSpreadChild = assertJSXSpreadChild; + exports.assertJSXIdentifier = assertJSXIdentifier; + exports.assertJSXMemberExpression = assertJSXMemberExpression; + exports.assertJSXNamespacedName = assertJSXNamespacedName; + exports.assertJSXOpeningElement = assertJSXOpeningElement; + exports.assertJSXSpreadAttribute = assertJSXSpreadAttribute; + exports.assertJSXText = assertJSXText; + exports.assertJSXFragment = assertJSXFragment; + exports.assertJSXOpeningFragment = assertJSXOpeningFragment; + exports.assertJSXClosingFragment = assertJSXClosingFragment; + exports.assertNoop = assertNoop; + exports.assertPlaceholder = assertPlaceholder; + exports.assertV8IntrinsicIdentifier = assertV8IntrinsicIdentifier; + exports.assertArgumentPlaceholder = assertArgumentPlaceholder; + exports.assertBindExpression = assertBindExpression; + exports.assertClassProperty = assertClassProperty; + exports.assertPipelineTopicExpression = assertPipelineTopicExpression; + exports.assertPipelineBareFunction = assertPipelineBareFunction; + exports.assertPipelinePrimaryTopicReference = assertPipelinePrimaryTopicReference; + exports.assertClassPrivateProperty = assertClassPrivateProperty; + exports.assertClassPrivateMethod = assertClassPrivateMethod; + exports.assertImportAttribute = assertImportAttribute; + exports.assertDecorator = assertDecorator; + exports.assertDoExpression = assertDoExpression; + exports.assertExportDefaultSpecifier = assertExportDefaultSpecifier; + exports.assertPrivateName = assertPrivateName; + exports.assertRecordExpression = assertRecordExpression; + exports.assertTupleExpression = assertTupleExpression; + exports.assertDecimalLiteral = assertDecimalLiteral; + exports.assertStaticBlock = assertStaticBlock; + exports.assertTSParameterProperty = assertTSParameterProperty; + exports.assertTSDeclareFunction = assertTSDeclareFunction; + exports.assertTSDeclareMethod = assertTSDeclareMethod; + exports.assertTSQualifiedName = assertTSQualifiedName; + exports.assertTSCallSignatureDeclaration = assertTSCallSignatureDeclaration; + exports.assertTSConstructSignatureDeclaration = assertTSConstructSignatureDeclaration; + exports.assertTSPropertySignature = assertTSPropertySignature; + exports.assertTSMethodSignature = assertTSMethodSignature; + exports.assertTSIndexSignature = assertTSIndexSignature; + exports.assertTSAnyKeyword = assertTSAnyKeyword; + exports.assertTSBooleanKeyword = assertTSBooleanKeyword; + exports.assertTSBigIntKeyword = assertTSBigIntKeyword; + exports.assertTSIntrinsicKeyword = assertTSIntrinsicKeyword; + exports.assertTSNeverKeyword = assertTSNeverKeyword; + exports.assertTSNullKeyword = assertTSNullKeyword; + exports.assertTSNumberKeyword = assertTSNumberKeyword; + exports.assertTSObjectKeyword = assertTSObjectKeyword; + exports.assertTSStringKeyword = assertTSStringKeyword; + exports.assertTSSymbolKeyword = assertTSSymbolKeyword; + exports.assertTSUndefinedKeyword = assertTSUndefinedKeyword; + exports.assertTSUnknownKeyword = assertTSUnknownKeyword; + exports.assertTSVoidKeyword = assertTSVoidKeyword; + exports.assertTSThisType = assertTSThisType; + exports.assertTSFunctionType = assertTSFunctionType; + exports.assertTSConstructorType = assertTSConstructorType; + exports.assertTSTypeReference = assertTSTypeReference; + exports.assertTSTypePredicate = assertTSTypePredicate; + exports.assertTSTypeQuery = assertTSTypeQuery; + exports.assertTSTypeLiteral = assertTSTypeLiteral; + exports.assertTSArrayType = assertTSArrayType; + exports.assertTSTupleType = assertTSTupleType; + exports.assertTSOptionalType = assertTSOptionalType; + exports.assertTSRestType = assertTSRestType; + exports.assertTSNamedTupleMember = assertTSNamedTupleMember; + exports.assertTSUnionType = assertTSUnionType; + exports.assertTSIntersectionType = assertTSIntersectionType; + exports.assertTSConditionalType = assertTSConditionalType; + exports.assertTSInferType = assertTSInferType; + exports.assertTSParenthesizedType = assertTSParenthesizedType; + exports.assertTSTypeOperator = assertTSTypeOperator; + exports.assertTSIndexedAccessType = assertTSIndexedAccessType; + exports.assertTSMappedType = assertTSMappedType; + exports.assertTSLiteralType = assertTSLiteralType; + exports.assertTSExpressionWithTypeArguments = assertTSExpressionWithTypeArguments; + exports.assertTSInterfaceDeclaration = assertTSInterfaceDeclaration; + exports.assertTSInterfaceBody = assertTSInterfaceBody; + exports.assertTSTypeAliasDeclaration = assertTSTypeAliasDeclaration; + exports.assertTSAsExpression = assertTSAsExpression; + exports.assertTSTypeAssertion = assertTSTypeAssertion; + exports.assertTSEnumDeclaration = assertTSEnumDeclaration; + exports.assertTSEnumMember = assertTSEnumMember; + exports.assertTSModuleDeclaration = assertTSModuleDeclaration; + exports.assertTSModuleBlock = assertTSModuleBlock; + exports.assertTSImportType = assertTSImportType; + exports.assertTSImportEqualsDeclaration = assertTSImportEqualsDeclaration; + exports.assertTSExternalModuleReference = assertTSExternalModuleReference; + exports.assertTSNonNullExpression = assertTSNonNullExpression; + exports.assertTSExportAssignment = assertTSExportAssignment; + exports.assertTSNamespaceExportDeclaration = assertTSNamespaceExportDeclaration; + exports.assertTSTypeAnnotation = assertTSTypeAnnotation; + exports.assertTSTypeParameterInstantiation = assertTSTypeParameterInstantiation; + exports.assertTSTypeParameterDeclaration = assertTSTypeParameterDeclaration; + exports.assertTSTypeParameter = assertTSTypeParameter; + exports.assertExpression = assertExpression; + exports.assertBinary = assertBinary; + exports.assertScopable = assertScopable; + exports.assertBlockParent = assertBlockParent; + exports.assertBlock = assertBlock; + exports.assertStatement = assertStatement; + exports.assertTerminatorless = assertTerminatorless; + exports.assertCompletionStatement = assertCompletionStatement; + exports.assertConditional = assertConditional; + exports.assertLoop = assertLoop; + exports.assertWhile = assertWhile; + exports.assertExpressionWrapper = assertExpressionWrapper; + exports.assertFor = assertFor; + exports.assertForXStatement = assertForXStatement; + exports.assertFunction = assertFunction; + exports.assertFunctionParent = assertFunctionParent; + exports.assertPureish = assertPureish; + exports.assertDeclaration = assertDeclaration; + exports.assertPatternLike = assertPatternLike; + exports.assertLVal = assertLVal; + exports.assertTSEntityName = assertTSEntityName; + exports.assertLiteral = assertLiteral; + exports.assertImmutable = assertImmutable; + exports.assertUserWhitespacable = assertUserWhitespacable; + exports.assertMethod = assertMethod; + exports.assertObjectMember = assertObjectMember; + exports.assertProperty = assertProperty; + exports.assertUnaryLike = assertUnaryLike; + exports.assertPattern = assertPattern; + exports.assertClass = assertClass; + exports.assertModuleDeclaration = assertModuleDeclaration; + exports.assertExportDeclaration = assertExportDeclaration; + exports.assertModuleSpecifier = assertModuleSpecifier; + exports.assertFlow = assertFlow; + exports.assertFlowType = assertFlowType; + exports.assertFlowBaseAnnotation = assertFlowBaseAnnotation; + exports.assertFlowDeclaration = assertFlowDeclaration; + exports.assertFlowPredicate = assertFlowPredicate; + exports.assertEnumBody = assertEnumBody; + exports.assertEnumMember = assertEnumMember; + exports.assertJSX = assertJSX; + exports.assertPrivate = assertPrivate; + exports.assertTSTypeElement = assertTSTypeElement; + exports.assertTSType = assertTSType; + exports.assertTSBaseType = assertTSBaseType; + exports.assertNumberLiteral = assertNumberLiteral; + exports.assertRegexLiteral = assertRegexLiteral; + exports.assertRestProperty = assertRestProperty; + exports.assertSpreadProperty = assertSpreadProperty; + + var _is = _interopRequireDefault(is_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function assert(type, node, opts) { + if (!(0, _is.default)(type, node, opts)) { + throw new Error(`Expected type "${type}" with option ${JSON.stringify(opts)}, ` + `but instead got "${node.type}".`); + } + } + + function assertArrayExpression(node, opts = {}) { + assert("ArrayExpression", node, opts); + } + + function assertAssignmentExpression(node, opts = {}) { + assert("AssignmentExpression", node, opts); + } + + function assertBinaryExpression(node, opts = {}) { + assert("BinaryExpression", node, opts); + } + + function assertInterpreterDirective(node, opts = {}) { + assert("InterpreterDirective", node, opts); + } + + function assertDirective(node, opts = {}) { + assert("Directive", node, opts); + } + + function assertDirectiveLiteral(node, opts = {}) { + assert("DirectiveLiteral", node, opts); + } + + function assertBlockStatement(node, opts = {}) { + assert("BlockStatement", node, opts); + } + + function assertBreakStatement(node, opts = {}) { + assert("BreakStatement", node, opts); + } + + function assertCallExpression(node, opts = {}) { + assert("CallExpression", node, opts); + } + + function assertCatchClause(node, opts = {}) { + assert("CatchClause", node, opts); + } + + function assertConditionalExpression(node, opts = {}) { + assert("ConditionalExpression", node, opts); + } + + function assertContinueStatement(node, opts = {}) { + assert("ContinueStatement", node, opts); + } + + function assertDebuggerStatement(node, opts = {}) { + assert("DebuggerStatement", node, opts); + } + + function assertDoWhileStatement(node, opts = {}) { + assert("DoWhileStatement", node, opts); + } + + function assertEmptyStatement(node, opts = {}) { + assert("EmptyStatement", node, opts); + } + + function assertExpressionStatement(node, opts = {}) { + assert("ExpressionStatement", node, opts); + } + + function assertFile(node, opts = {}) { + assert("File", node, opts); + } + + function assertForInStatement(node, opts = {}) { + assert("ForInStatement", node, opts); + } + + function assertForStatement(node, opts = {}) { + assert("ForStatement", node, opts); + } + + function assertFunctionDeclaration(node, opts = {}) { + assert("FunctionDeclaration", node, opts); + } + + function assertFunctionExpression(node, opts = {}) { + assert("FunctionExpression", node, opts); + } + + function assertIdentifier(node, opts = {}) { + assert("Identifier", node, opts); + } + + function assertIfStatement(node, opts = {}) { + assert("IfStatement", node, opts); + } + + function assertLabeledStatement(node, opts = {}) { + assert("LabeledStatement", node, opts); + } + + function assertStringLiteral(node, opts = {}) { + assert("StringLiteral", node, opts); + } + + function assertNumericLiteral(node, opts = {}) { + assert("NumericLiteral", node, opts); + } + + function assertNullLiteral(node, opts = {}) { + assert("NullLiteral", node, opts); + } + + function assertBooleanLiteral(node, opts = {}) { + assert("BooleanLiteral", node, opts); + } + + function assertRegExpLiteral(node, opts = {}) { + assert("RegExpLiteral", node, opts); + } + + function assertLogicalExpression(node, opts = {}) { + assert("LogicalExpression", node, opts); + } + + function assertMemberExpression(node, opts = {}) { + assert("MemberExpression", node, opts); + } + + function assertNewExpression(node, opts = {}) { + assert("NewExpression", node, opts); + } + + function assertProgram(node, opts = {}) { + assert("Program", node, opts); + } + + function assertObjectExpression(node, opts = {}) { + assert("ObjectExpression", node, opts); + } + + function assertObjectMethod(node, opts = {}) { + assert("ObjectMethod", node, opts); + } + + function assertObjectProperty(node, opts = {}) { + assert("ObjectProperty", node, opts); + } + + function assertRestElement(node, opts = {}) { + assert("RestElement", node, opts); + } + + function assertReturnStatement(node, opts = {}) { + assert("ReturnStatement", node, opts); + } + + function assertSequenceExpression(node, opts = {}) { + assert("SequenceExpression", node, opts); + } + + function assertParenthesizedExpression(node, opts = {}) { + assert("ParenthesizedExpression", node, opts); + } + + function assertSwitchCase(node, opts = {}) { + assert("SwitchCase", node, opts); + } + + function assertSwitchStatement(node, opts = {}) { + assert("SwitchStatement", node, opts); + } + + function assertThisExpression(node, opts = {}) { + assert("ThisExpression", node, opts); + } + + function assertThrowStatement(node, opts = {}) { + assert("ThrowStatement", node, opts); + } + + function assertTryStatement(node, opts = {}) { + assert("TryStatement", node, opts); + } + + function assertUnaryExpression(node, opts = {}) { + assert("UnaryExpression", node, opts); + } + + function assertUpdateExpression(node, opts = {}) { + assert("UpdateExpression", node, opts); + } + + function assertVariableDeclaration(node, opts = {}) { + assert("VariableDeclaration", node, opts); + } + + function assertVariableDeclarator(node, opts = {}) { + assert("VariableDeclarator", node, opts); + } + + function assertWhileStatement(node, opts = {}) { + assert("WhileStatement", node, opts); + } + + function assertWithStatement(node, opts = {}) { + assert("WithStatement", node, opts); + } + + function assertAssignmentPattern(node, opts = {}) { + assert("AssignmentPattern", node, opts); + } + + function assertArrayPattern(node, opts = {}) { + assert("ArrayPattern", node, opts); + } + + function assertArrowFunctionExpression(node, opts = {}) { + assert("ArrowFunctionExpression", node, opts); + } + + function assertClassBody(node, opts = {}) { + assert("ClassBody", node, opts); + } + + function assertClassExpression(node, opts = {}) { + assert("ClassExpression", node, opts); + } + + function assertClassDeclaration(node, opts = {}) { + assert("ClassDeclaration", node, opts); + } + + function assertExportAllDeclaration(node, opts = {}) { + assert("ExportAllDeclaration", node, opts); + } + + function assertExportDefaultDeclaration(node, opts = {}) { + assert("ExportDefaultDeclaration", node, opts); + } + + function assertExportNamedDeclaration(node, opts = {}) { + assert("ExportNamedDeclaration", node, opts); + } + + function assertExportSpecifier(node, opts = {}) { + assert("ExportSpecifier", node, opts); + } + + function assertForOfStatement(node, opts = {}) { + assert("ForOfStatement", node, opts); + } + + function assertImportDeclaration(node, opts = {}) { + assert("ImportDeclaration", node, opts); + } + + function assertImportDefaultSpecifier(node, opts = {}) { + assert("ImportDefaultSpecifier", node, opts); + } + + function assertImportNamespaceSpecifier(node, opts = {}) { + assert("ImportNamespaceSpecifier", node, opts); + } + + function assertImportSpecifier(node, opts = {}) { + assert("ImportSpecifier", node, opts); + } + + function assertMetaProperty(node, opts = {}) { + assert("MetaProperty", node, opts); + } + + function assertClassMethod(node, opts = {}) { + assert("ClassMethod", node, opts); + } + + function assertObjectPattern(node, opts = {}) { + assert("ObjectPattern", node, opts); + } + + function assertSpreadElement(node, opts = {}) { + assert("SpreadElement", node, opts); + } + + function assertSuper(node, opts = {}) { + assert("Super", node, opts); + } + + function assertTaggedTemplateExpression(node, opts = {}) { + assert("TaggedTemplateExpression", node, opts); + } + + function assertTemplateElement(node, opts = {}) { + assert("TemplateElement", node, opts); + } + + function assertTemplateLiteral(node, opts = {}) { + assert("TemplateLiteral", node, opts); + } + + function assertYieldExpression(node, opts = {}) { + assert("YieldExpression", node, opts); + } + + function assertAwaitExpression(node, opts = {}) { + assert("AwaitExpression", node, opts); + } + + function assertImport(node, opts = {}) { + assert("Import", node, opts); + } + + function assertBigIntLiteral(node, opts = {}) { + assert("BigIntLiteral", node, opts); + } + + function assertExportNamespaceSpecifier(node, opts = {}) { + assert("ExportNamespaceSpecifier", node, opts); + } + + function assertOptionalMemberExpression(node, opts = {}) { + assert("OptionalMemberExpression", node, opts); + } + + function assertOptionalCallExpression(node, opts = {}) { + assert("OptionalCallExpression", node, opts); + } + + function assertAnyTypeAnnotation(node, opts = {}) { + assert("AnyTypeAnnotation", node, opts); + } + + function assertArrayTypeAnnotation(node, opts = {}) { + assert("ArrayTypeAnnotation", node, opts); + } + + function assertBooleanTypeAnnotation(node, opts = {}) { + assert("BooleanTypeAnnotation", node, opts); + } + + function assertBooleanLiteralTypeAnnotation(node, opts = {}) { + assert("BooleanLiteralTypeAnnotation", node, opts); + } + + function assertNullLiteralTypeAnnotation(node, opts = {}) { + assert("NullLiteralTypeAnnotation", node, opts); + } + + function assertClassImplements(node, opts = {}) { + assert("ClassImplements", node, opts); + } + + function assertDeclareClass(node, opts = {}) { + assert("DeclareClass", node, opts); + } + + function assertDeclareFunction(node, opts = {}) { + assert("DeclareFunction", node, opts); + } + + function assertDeclareInterface(node, opts = {}) { + assert("DeclareInterface", node, opts); + } + + function assertDeclareModule(node, opts = {}) { + assert("DeclareModule", node, opts); + } + + function assertDeclareModuleExports(node, opts = {}) { + assert("DeclareModuleExports", node, opts); + } + + function assertDeclareTypeAlias(node, opts = {}) { + assert("DeclareTypeAlias", node, opts); + } + + function assertDeclareOpaqueType(node, opts = {}) { + assert("DeclareOpaqueType", node, opts); + } + + function assertDeclareVariable(node, opts = {}) { + assert("DeclareVariable", node, opts); + } + + function assertDeclareExportDeclaration(node, opts = {}) { + assert("DeclareExportDeclaration", node, opts); + } + + function assertDeclareExportAllDeclaration(node, opts = {}) { + assert("DeclareExportAllDeclaration", node, opts); + } + + function assertDeclaredPredicate(node, opts = {}) { + assert("DeclaredPredicate", node, opts); + } + + function assertExistsTypeAnnotation(node, opts = {}) { + assert("ExistsTypeAnnotation", node, opts); + } + + function assertFunctionTypeAnnotation(node, opts = {}) { + assert("FunctionTypeAnnotation", node, opts); + } + + function assertFunctionTypeParam(node, opts = {}) { + assert("FunctionTypeParam", node, opts); + } + + function assertGenericTypeAnnotation(node, opts = {}) { + assert("GenericTypeAnnotation", node, opts); + } + + function assertInferredPredicate(node, opts = {}) { + assert("InferredPredicate", node, opts); + } + + function assertInterfaceExtends(node, opts = {}) { + assert("InterfaceExtends", node, opts); + } + + function assertInterfaceDeclaration(node, opts = {}) { + assert("InterfaceDeclaration", node, opts); + } + + function assertInterfaceTypeAnnotation(node, opts = {}) { + assert("InterfaceTypeAnnotation", node, opts); + } + + function assertIntersectionTypeAnnotation(node, opts = {}) { + assert("IntersectionTypeAnnotation", node, opts); + } + + function assertMixedTypeAnnotation(node, opts = {}) { + assert("MixedTypeAnnotation", node, opts); + } + + function assertEmptyTypeAnnotation(node, opts = {}) { + assert("EmptyTypeAnnotation", node, opts); + } + + function assertNullableTypeAnnotation(node, opts = {}) { + assert("NullableTypeAnnotation", node, opts); + } + + function assertNumberLiteralTypeAnnotation(node, opts = {}) { + assert("NumberLiteralTypeAnnotation", node, opts); + } + + function assertNumberTypeAnnotation(node, opts = {}) { + assert("NumberTypeAnnotation", node, opts); + } + + function assertObjectTypeAnnotation(node, opts = {}) { + assert("ObjectTypeAnnotation", node, opts); + } + + function assertObjectTypeInternalSlot(node, opts = {}) { + assert("ObjectTypeInternalSlot", node, opts); + } + + function assertObjectTypeCallProperty(node, opts = {}) { + assert("ObjectTypeCallProperty", node, opts); + } + + function assertObjectTypeIndexer(node, opts = {}) { + assert("ObjectTypeIndexer", node, opts); + } + + function assertObjectTypeProperty(node, opts = {}) { + assert("ObjectTypeProperty", node, opts); + } + + function assertObjectTypeSpreadProperty(node, opts = {}) { + assert("ObjectTypeSpreadProperty", node, opts); + } + + function assertOpaqueType(node, opts = {}) { + assert("OpaqueType", node, opts); + } + + function assertQualifiedTypeIdentifier(node, opts = {}) { + assert("QualifiedTypeIdentifier", node, opts); + } + + function assertStringLiteralTypeAnnotation(node, opts = {}) { + assert("StringLiteralTypeAnnotation", node, opts); + } + + function assertStringTypeAnnotation(node, opts = {}) { + assert("StringTypeAnnotation", node, opts); + } + + function assertSymbolTypeAnnotation(node, opts = {}) { + assert("SymbolTypeAnnotation", node, opts); + } + + function assertThisTypeAnnotation(node, opts = {}) { + assert("ThisTypeAnnotation", node, opts); + } + + function assertTupleTypeAnnotation(node, opts = {}) { + assert("TupleTypeAnnotation", node, opts); + } + + function assertTypeofTypeAnnotation(node, opts = {}) { + assert("TypeofTypeAnnotation", node, opts); + } + + function assertTypeAlias(node, opts = {}) { + assert("TypeAlias", node, opts); + } + + function assertTypeAnnotation(node, opts = {}) { + assert("TypeAnnotation", node, opts); + } + + function assertTypeCastExpression(node, opts = {}) { + assert("TypeCastExpression", node, opts); + } + + function assertTypeParameter(node, opts = {}) { + assert("TypeParameter", node, opts); + } + + function assertTypeParameterDeclaration(node, opts = {}) { + assert("TypeParameterDeclaration", node, opts); + } + + function assertTypeParameterInstantiation(node, opts = {}) { + assert("TypeParameterInstantiation", node, opts); + } + + function assertUnionTypeAnnotation(node, opts = {}) { + assert("UnionTypeAnnotation", node, opts); + } + + function assertVariance(node, opts = {}) { + assert("Variance", node, opts); + } + + function assertVoidTypeAnnotation(node, opts = {}) { + assert("VoidTypeAnnotation", node, opts); + } + + function assertEnumDeclaration(node, opts = {}) { + assert("EnumDeclaration", node, opts); + } + + function assertEnumBooleanBody(node, opts = {}) { + assert("EnumBooleanBody", node, opts); + } + + function assertEnumNumberBody(node, opts = {}) { + assert("EnumNumberBody", node, opts); + } + + function assertEnumStringBody(node, opts = {}) { + assert("EnumStringBody", node, opts); + } + + function assertEnumSymbolBody(node, opts = {}) { + assert("EnumSymbolBody", node, opts); + } + + function assertEnumBooleanMember(node, opts = {}) { + assert("EnumBooleanMember", node, opts); + } + + function assertEnumNumberMember(node, opts = {}) { + assert("EnumNumberMember", node, opts); + } + + function assertEnumStringMember(node, opts = {}) { + assert("EnumStringMember", node, opts); + } + + function assertEnumDefaultedMember(node, opts = {}) { + assert("EnumDefaultedMember", node, opts); + } + + function assertJSXAttribute(node, opts = {}) { + assert("JSXAttribute", node, opts); + } + + function assertJSXClosingElement(node, opts = {}) { + assert("JSXClosingElement", node, opts); + } + + function assertJSXElement(node, opts = {}) { + assert("JSXElement", node, opts); + } + + function assertJSXEmptyExpression(node, opts = {}) { + assert("JSXEmptyExpression", node, opts); + } + + function assertJSXExpressionContainer(node, opts = {}) { + assert("JSXExpressionContainer", node, opts); + } + + function assertJSXSpreadChild(node, opts = {}) { + assert("JSXSpreadChild", node, opts); + } + + function assertJSXIdentifier(node, opts = {}) { + assert("JSXIdentifier", node, opts); + } + + function assertJSXMemberExpression(node, opts = {}) { + assert("JSXMemberExpression", node, opts); + } + + function assertJSXNamespacedName(node, opts = {}) { + assert("JSXNamespacedName", node, opts); + } + + function assertJSXOpeningElement(node, opts = {}) { + assert("JSXOpeningElement", node, opts); + } + + function assertJSXSpreadAttribute(node, opts = {}) { + assert("JSXSpreadAttribute", node, opts); + } + + function assertJSXText(node, opts = {}) { + assert("JSXText", node, opts); + } + + function assertJSXFragment(node, opts = {}) { + assert("JSXFragment", node, opts); + } + + function assertJSXOpeningFragment(node, opts = {}) { + assert("JSXOpeningFragment", node, opts); + } + + function assertJSXClosingFragment(node, opts = {}) { + assert("JSXClosingFragment", node, opts); + } + + function assertNoop(node, opts = {}) { + assert("Noop", node, opts); + } + + function assertPlaceholder(node, opts = {}) { + assert("Placeholder", node, opts); + } + + function assertV8IntrinsicIdentifier(node, opts = {}) { + assert("V8IntrinsicIdentifier", node, opts); + } + + function assertArgumentPlaceholder(node, opts = {}) { + assert("ArgumentPlaceholder", node, opts); + } + + function assertBindExpression(node, opts = {}) { + assert("BindExpression", node, opts); + } + + function assertClassProperty(node, opts = {}) { + assert("ClassProperty", node, opts); + } + + function assertPipelineTopicExpression(node, opts = {}) { + assert("PipelineTopicExpression", node, opts); + } + + function assertPipelineBareFunction(node, opts = {}) { + assert("PipelineBareFunction", node, opts); + } + + function assertPipelinePrimaryTopicReference(node, opts = {}) { + assert("PipelinePrimaryTopicReference", node, opts); + } + + function assertClassPrivateProperty(node, opts = {}) { + assert("ClassPrivateProperty", node, opts); + } + + function assertClassPrivateMethod(node, opts = {}) { + assert("ClassPrivateMethod", node, opts); + } + + function assertImportAttribute(node, opts = {}) { + assert("ImportAttribute", node, opts); + } + + function assertDecorator(node, opts = {}) { + assert("Decorator", node, opts); + } + + function assertDoExpression(node, opts = {}) { + assert("DoExpression", node, opts); + } + + function assertExportDefaultSpecifier(node, opts = {}) { + assert("ExportDefaultSpecifier", node, opts); + } + + function assertPrivateName(node, opts = {}) { + assert("PrivateName", node, opts); + } + + function assertRecordExpression(node, opts = {}) { + assert("RecordExpression", node, opts); + } + + function assertTupleExpression(node, opts = {}) { + assert("TupleExpression", node, opts); + } + + function assertDecimalLiteral(node, opts = {}) { + assert("DecimalLiteral", node, opts); + } + + function assertStaticBlock(node, opts = {}) { + assert("StaticBlock", node, opts); + } + + function assertTSParameterProperty(node, opts = {}) { + assert("TSParameterProperty", node, opts); + } + + function assertTSDeclareFunction(node, opts = {}) { + assert("TSDeclareFunction", node, opts); + } + + function assertTSDeclareMethod(node, opts = {}) { + assert("TSDeclareMethod", node, opts); + } + + function assertTSQualifiedName(node, opts = {}) { + assert("TSQualifiedName", node, opts); + } + + function assertTSCallSignatureDeclaration(node, opts = {}) { + assert("TSCallSignatureDeclaration", node, opts); + } + + function assertTSConstructSignatureDeclaration(node, opts = {}) { + assert("TSConstructSignatureDeclaration", node, opts); + } + + function assertTSPropertySignature(node, opts = {}) { + assert("TSPropertySignature", node, opts); + } + + function assertTSMethodSignature(node, opts = {}) { + assert("TSMethodSignature", node, opts); + } + + function assertTSIndexSignature(node, opts = {}) { + assert("TSIndexSignature", node, opts); + } + + function assertTSAnyKeyword(node, opts = {}) { + assert("TSAnyKeyword", node, opts); + } + + function assertTSBooleanKeyword(node, opts = {}) { + assert("TSBooleanKeyword", node, opts); + } + + function assertTSBigIntKeyword(node, opts = {}) { + assert("TSBigIntKeyword", node, opts); + } + + function assertTSIntrinsicKeyword(node, opts = {}) { + assert("TSIntrinsicKeyword", node, opts); + } + + function assertTSNeverKeyword(node, opts = {}) { + assert("TSNeverKeyword", node, opts); + } + + function assertTSNullKeyword(node, opts = {}) { + assert("TSNullKeyword", node, opts); + } + + function assertTSNumberKeyword(node, opts = {}) { + assert("TSNumberKeyword", node, opts); + } + + function assertTSObjectKeyword(node, opts = {}) { + assert("TSObjectKeyword", node, opts); + } + + function assertTSStringKeyword(node, opts = {}) { + assert("TSStringKeyword", node, opts); + } + + function assertTSSymbolKeyword(node, opts = {}) { + assert("TSSymbolKeyword", node, opts); + } + + function assertTSUndefinedKeyword(node, opts = {}) { + assert("TSUndefinedKeyword", node, opts); + } + + function assertTSUnknownKeyword(node, opts = {}) { + assert("TSUnknownKeyword", node, opts); + } + + function assertTSVoidKeyword(node, opts = {}) { + assert("TSVoidKeyword", node, opts); + } + + function assertTSThisType(node, opts = {}) { + assert("TSThisType", node, opts); + } + + function assertTSFunctionType(node, opts = {}) { + assert("TSFunctionType", node, opts); + } + + function assertTSConstructorType(node, opts = {}) { + assert("TSConstructorType", node, opts); + } + + function assertTSTypeReference(node, opts = {}) { + assert("TSTypeReference", node, opts); + } + + function assertTSTypePredicate(node, opts = {}) { + assert("TSTypePredicate", node, opts); + } + + function assertTSTypeQuery(node, opts = {}) { + assert("TSTypeQuery", node, opts); + } + + function assertTSTypeLiteral(node, opts = {}) { + assert("TSTypeLiteral", node, opts); + } + + function assertTSArrayType(node, opts = {}) { + assert("TSArrayType", node, opts); + } + + function assertTSTupleType(node, opts = {}) { + assert("TSTupleType", node, opts); + } + + function assertTSOptionalType(node, opts = {}) { + assert("TSOptionalType", node, opts); + } + + function assertTSRestType(node, opts = {}) { + assert("TSRestType", node, opts); + } + + function assertTSNamedTupleMember(node, opts = {}) { + assert("TSNamedTupleMember", node, opts); + } + + function assertTSUnionType(node, opts = {}) { + assert("TSUnionType", node, opts); + } + + function assertTSIntersectionType(node, opts = {}) { + assert("TSIntersectionType", node, opts); + } + + function assertTSConditionalType(node, opts = {}) { + assert("TSConditionalType", node, opts); + } + + function assertTSInferType(node, opts = {}) { + assert("TSInferType", node, opts); + } + + function assertTSParenthesizedType(node, opts = {}) { + assert("TSParenthesizedType", node, opts); + } + + function assertTSTypeOperator(node, opts = {}) { + assert("TSTypeOperator", node, opts); + } + + function assertTSIndexedAccessType(node, opts = {}) { + assert("TSIndexedAccessType", node, opts); + } + + function assertTSMappedType(node, opts = {}) { + assert("TSMappedType", node, opts); + } + + function assertTSLiteralType(node, opts = {}) { + assert("TSLiteralType", node, opts); + } + + function assertTSExpressionWithTypeArguments(node, opts = {}) { + assert("TSExpressionWithTypeArguments", node, opts); + } + + function assertTSInterfaceDeclaration(node, opts = {}) { + assert("TSInterfaceDeclaration", node, opts); + } + + function assertTSInterfaceBody(node, opts = {}) { + assert("TSInterfaceBody", node, opts); + } + + function assertTSTypeAliasDeclaration(node, opts = {}) { + assert("TSTypeAliasDeclaration", node, opts); + } + + function assertTSAsExpression(node, opts = {}) { + assert("TSAsExpression", node, opts); + } + + function assertTSTypeAssertion(node, opts = {}) { + assert("TSTypeAssertion", node, opts); + } + + function assertTSEnumDeclaration(node, opts = {}) { + assert("TSEnumDeclaration", node, opts); + } + + function assertTSEnumMember(node, opts = {}) { + assert("TSEnumMember", node, opts); + } + + function assertTSModuleDeclaration(node, opts = {}) { + assert("TSModuleDeclaration", node, opts); + } + + function assertTSModuleBlock(node, opts = {}) { + assert("TSModuleBlock", node, opts); + } + + function assertTSImportType(node, opts = {}) { + assert("TSImportType", node, opts); + } + + function assertTSImportEqualsDeclaration(node, opts = {}) { + assert("TSImportEqualsDeclaration", node, opts); + } + + function assertTSExternalModuleReference(node, opts = {}) { + assert("TSExternalModuleReference", node, opts); + } + + function assertTSNonNullExpression(node, opts = {}) { + assert("TSNonNullExpression", node, opts); + } + + function assertTSExportAssignment(node, opts = {}) { + assert("TSExportAssignment", node, opts); + } + + function assertTSNamespaceExportDeclaration(node, opts = {}) { + assert("TSNamespaceExportDeclaration", node, opts); + } + + function assertTSTypeAnnotation(node, opts = {}) { + assert("TSTypeAnnotation", node, opts); + } + + function assertTSTypeParameterInstantiation(node, opts = {}) { + assert("TSTypeParameterInstantiation", node, opts); + } + + function assertTSTypeParameterDeclaration(node, opts = {}) { + assert("TSTypeParameterDeclaration", node, opts); + } + + function assertTSTypeParameter(node, opts = {}) { + assert("TSTypeParameter", node, opts); + } + + function assertExpression(node, opts = {}) { + assert("Expression", node, opts); + } + + function assertBinary(node, opts = {}) { + assert("Binary", node, opts); + } + + function assertScopable(node, opts = {}) { + assert("Scopable", node, opts); + } + + function assertBlockParent(node, opts = {}) { + assert("BlockParent", node, opts); + } + + function assertBlock(node, opts = {}) { + assert("Block", node, opts); + } + + function assertStatement(node, opts = {}) { + assert("Statement", node, opts); + } + + function assertTerminatorless(node, opts = {}) { + assert("Terminatorless", node, opts); + } + + function assertCompletionStatement(node, opts = {}) { + assert("CompletionStatement", node, opts); + } + + function assertConditional(node, opts = {}) { + assert("Conditional", node, opts); + } + + function assertLoop(node, opts = {}) { + assert("Loop", node, opts); + } + + function assertWhile(node, opts = {}) { + assert("While", node, opts); + } + + function assertExpressionWrapper(node, opts = {}) { + assert("ExpressionWrapper", node, opts); + } + + function assertFor(node, opts = {}) { + assert("For", node, opts); + } + + function assertForXStatement(node, opts = {}) { + assert("ForXStatement", node, opts); + } + + function assertFunction(node, opts = {}) { + assert("Function", node, opts); + } + + function assertFunctionParent(node, opts = {}) { + assert("FunctionParent", node, opts); + } + + function assertPureish(node, opts = {}) { + assert("Pureish", node, opts); + } + + function assertDeclaration(node, opts = {}) { + assert("Declaration", node, opts); + } + + function assertPatternLike(node, opts = {}) { + assert("PatternLike", node, opts); + } + + function assertLVal(node, opts = {}) { + assert("LVal", node, opts); + } + + function assertTSEntityName(node, opts = {}) { + assert("TSEntityName", node, opts); + } + + function assertLiteral(node, opts = {}) { + assert("Literal", node, opts); + } + + function assertImmutable(node, opts = {}) { + assert("Immutable", node, opts); + } + + function assertUserWhitespacable(node, opts = {}) { + assert("UserWhitespacable", node, opts); + } + + function assertMethod(node, opts = {}) { + assert("Method", node, opts); + } + + function assertObjectMember(node, opts = {}) { + assert("ObjectMember", node, opts); + } + + function assertProperty(node, opts = {}) { + assert("Property", node, opts); + } + + function assertUnaryLike(node, opts = {}) { + assert("UnaryLike", node, opts); + } + + function assertPattern(node, opts = {}) { + assert("Pattern", node, opts); + } + + function assertClass(node, opts = {}) { + assert("Class", node, opts); + } + + function assertModuleDeclaration(node, opts = {}) { + assert("ModuleDeclaration", node, opts); + } + + function assertExportDeclaration(node, opts = {}) { + assert("ExportDeclaration", node, opts); + } + + function assertModuleSpecifier(node, opts = {}) { + assert("ModuleSpecifier", node, opts); + } + + function assertFlow(node, opts = {}) { + assert("Flow", node, opts); + } + + function assertFlowType(node, opts = {}) { + assert("FlowType", node, opts); + } + + function assertFlowBaseAnnotation(node, opts = {}) { + assert("FlowBaseAnnotation", node, opts); + } + + function assertFlowDeclaration(node, opts = {}) { + assert("FlowDeclaration", node, opts); + } + + function assertFlowPredicate(node, opts = {}) { + assert("FlowPredicate", node, opts); + } + + function assertEnumBody(node, opts = {}) { + assert("EnumBody", node, opts); + } + + function assertEnumMember(node, opts = {}) { + assert("EnumMember", node, opts); + } + + function assertJSX(node, opts = {}) { + assert("JSX", node, opts); + } + + function assertPrivate(node, opts = {}) { + assert("Private", node, opts); + } + + function assertTSTypeElement(node, opts = {}) { + assert("TSTypeElement", node, opts); + } + + function assertTSType(node, opts = {}) { + assert("TSType", node, opts); + } + + function assertTSBaseType(node, opts = {}) { + assert("TSBaseType", node, opts); + } + + function assertNumberLiteral(node, opts) { + console.trace("The node type NumberLiteral has been renamed to NumericLiteral"); + assert("NumberLiteral", node, opts); + } + + function assertRegexLiteral(node, opts) { + console.trace("The node type RegexLiteral has been renamed to RegExpLiteral"); + assert("RegexLiteral", node, opts); + } + + function assertRestProperty(node, opts) { + console.trace("The node type RestProperty has been renamed to RestElement"); + assert("RestProperty", node, opts); + } + + function assertSpreadProperty(node, opts) { + console.trace("The node type SpreadProperty has been renamed to SpreadElement"); + assert("SpreadProperty", node, opts); + } + }); + + unwrapExports(generated$2); + var generated_1$2 = generated$2.assertArrayExpression; + var generated_2$2 = generated$2.assertAssignmentExpression; + var generated_3$2 = generated$2.assertBinaryExpression; + var generated_4$2 = generated$2.assertInterpreterDirective; + var generated_5$2 = generated$2.assertDirective; + var generated_6$2 = generated$2.assertDirectiveLiteral; + var generated_7$2 = generated$2.assertBlockStatement; + var generated_8$2 = generated$2.assertBreakStatement; + var generated_9$2 = generated$2.assertCallExpression; + var generated_10$2 = generated$2.assertCatchClause; + var generated_11$2 = generated$2.assertConditionalExpression; + var generated_12$2 = generated$2.assertContinueStatement; + var generated_13$2 = generated$2.assertDebuggerStatement; + var generated_14$2 = generated$2.assertDoWhileStatement; + var generated_15$2 = generated$2.assertEmptyStatement; + var generated_16$2 = generated$2.assertExpressionStatement; + var generated_17$2 = generated$2.assertFile; + var generated_18$2 = generated$2.assertForInStatement; + var generated_19$2 = generated$2.assertForStatement; + var generated_20$2 = generated$2.assertFunctionDeclaration; + var generated_21$2 = generated$2.assertFunctionExpression; + var generated_22$2 = generated$2.assertIdentifier; + var generated_23$2 = generated$2.assertIfStatement; + var generated_24$2 = generated$2.assertLabeledStatement; + var generated_25$2 = generated$2.assertStringLiteral; + var generated_26$2 = generated$2.assertNumericLiteral; + var generated_27$2 = generated$2.assertNullLiteral; + var generated_28$2 = generated$2.assertBooleanLiteral; + var generated_29$2 = generated$2.assertRegExpLiteral; + var generated_30$2 = generated$2.assertLogicalExpression; + var generated_31$2 = generated$2.assertMemberExpression; + var generated_32$2 = generated$2.assertNewExpression; + var generated_33$2 = generated$2.assertProgram; + var generated_34$2 = generated$2.assertObjectExpression; + var generated_35$2 = generated$2.assertObjectMethod; + var generated_36$2 = generated$2.assertObjectProperty; + var generated_37$2 = generated$2.assertRestElement; + var generated_38$2 = generated$2.assertReturnStatement; + var generated_39$2 = generated$2.assertSequenceExpression; + var generated_40$2 = generated$2.assertParenthesizedExpression; + var generated_41$2 = generated$2.assertSwitchCase; + var generated_42$2 = generated$2.assertSwitchStatement; + var generated_43$2 = generated$2.assertThisExpression; + var generated_44$2 = generated$2.assertThrowStatement; + var generated_45$2 = generated$2.assertTryStatement; + var generated_46$2 = generated$2.assertUnaryExpression; + var generated_47$2 = generated$2.assertUpdateExpression; + var generated_48$2 = generated$2.assertVariableDeclaration; + var generated_49$2 = generated$2.assertVariableDeclarator; + var generated_50$2 = generated$2.assertWhileStatement; + var generated_51$2 = generated$2.assertWithStatement; + var generated_52$2 = generated$2.assertAssignmentPattern; + var generated_53$2 = generated$2.assertArrayPattern; + var generated_54$2 = generated$2.assertArrowFunctionExpression; + var generated_55$2 = generated$2.assertClassBody; + var generated_56$2 = generated$2.assertClassExpression; + var generated_57$2 = generated$2.assertClassDeclaration; + var generated_58$2 = generated$2.assertExportAllDeclaration; + var generated_59$2 = generated$2.assertExportDefaultDeclaration; + var generated_60$2 = generated$2.assertExportNamedDeclaration; + var generated_61$2 = generated$2.assertExportSpecifier; + var generated_62$2 = generated$2.assertForOfStatement; + var generated_63$2 = generated$2.assertImportDeclaration; + var generated_64$2 = generated$2.assertImportDefaultSpecifier; + var generated_65$2 = generated$2.assertImportNamespaceSpecifier; + var generated_66$2 = generated$2.assertImportSpecifier; + var generated_67$2 = generated$2.assertMetaProperty; + var generated_68$2 = generated$2.assertClassMethod; + var generated_69$2 = generated$2.assertObjectPattern; + var generated_70$2 = generated$2.assertSpreadElement; + var generated_71$2 = generated$2.assertSuper; + var generated_72$2 = generated$2.assertTaggedTemplateExpression; + var generated_73$2 = generated$2.assertTemplateElement; + var generated_74$2 = generated$2.assertTemplateLiteral; + var generated_75$2 = generated$2.assertYieldExpression; + var generated_76$2 = generated$2.assertAwaitExpression; + var generated_77$2 = generated$2.assertImport; + var generated_78$2 = generated$2.assertBigIntLiteral; + var generated_79$2 = generated$2.assertExportNamespaceSpecifier; + var generated_80$2 = generated$2.assertOptionalMemberExpression; + var generated_81$2 = generated$2.assertOptionalCallExpression; + var generated_82$2 = generated$2.assertAnyTypeAnnotation; + var generated_83$2 = generated$2.assertArrayTypeAnnotation; + var generated_84$2 = generated$2.assertBooleanTypeAnnotation; + var generated_85$2 = generated$2.assertBooleanLiteralTypeAnnotation; + var generated_86$2 = generated$2.assertNullLiteralTypeAnnotation; + var generated_87$2 = generated$2.assertClassImplements; + var generated_88$2 = generated$2.assertDeclareClass; + var generated_89$2 = generated$2.assertDeclareFunction; + var generated_90$2 = generated$2.assertDeclareInterface; + var generated_91$2 = generated$2.assertDeclareModule; + var generated_92$2 = generated$2.assertDeclareModuleExports; + var generated_93$2 = generated$2.assertDeclareTypeAlias; + var generated_94$2 = generated$2.assertDeclareOpaqueType; + var generated_95$2 = generated$2.assertDeclareVariable; + var generated_96$2 = generated$2.assertDeclareExportDeclaration; + var generated_97$2 = generated$2.assertDeclareExportAllDeclaration; + var generated_98$2 = generated$2.assertDeclaredPredicate; + var generated_99$2 = generated$2.assertExistsTypeAnnotation; + var generated_100$2 = generated$2.assertFunctionTypeAnnotation; + var generated_101$2 = generated$2.assertFunctionTypeParam; + var generated_102$2 = generated$2.assertGenericTypeAnnotation; + var generated_103$2 = generated$2.assertInferredPredicate; + var generated_104$2 = generated$2.assertInterfaceExtends; + var generated_105$2 = generated$2.assertInterfaceDeclaration; + var generated_106$2 = generated$2.assertInterfaceTypeAnnotation; + var generated_107$2 = generated$2.assertIntersectionTypeAnnotation; + var generated_108$2 = generated$2.assertMixedTypeAnnotation; + var generated_109$2 = generated$2.assertEmptyTypeAnnotation; + var generated_110$2 = generated$2.assertNullableTypeAnnotation; + var generated_111$2 = generated$2.assertNumberLiteralTypeAnnotation; + var generated_112$2 = generated$2.assertNumberTypeAnnotation; + var generated_113$2 = generated$2.assertObjectTypeAnnotation; + var generated_114$2 = generated$2.assertObjectTypeInternalSlot; + var generated_115$2 = generated$2.assertObjectTypeCallProperty; + var generated_116$2 = generated$2.assertObjectTypeIndexer; + var generated_117$2 = generated$2.assertObjectTypeProperty; + var generated_118$2 = generated$2.assertObjectTypeSpreadProperty; + var generated_119$2 = generated$2.assertOpaqueType; + var generated_120$2 = generated$2.assertQualifiedTypeIdentifier; + var generated_121$2 = generated$2.assertStringLiteralTypeAnnotation; + var generated_122$2 = generated$2.assertStringTypeAnnotation; + var generated_123$2 = generated$2.assertSymbolTypeAnnotation; + var generated_124$2 = generated$2.assertThisTypeAnnotation; + var generated_125$2 = generated$2.assertTupleTypeAnnotation; + var generated_126$2 = generated$2.assertTypeofTypeAnnotation; + var generated_127$2 = generated$2.assertTypeAlias; + var generated_128$2 = generated$2.assertTypeAnnotation; + var generated_129$2 = generated$2.assertTypeCastExpression; + var generated_130$2 = generated$2.assertTypeParameter; + var generated_131$2 = generated$2.assertTypeParameterDeclaration; + var generated_132$2 = generated$2.assertTypeParameterInstantiation; + var generated_133$2 = generated$2.assertUnionTypeAnnotation; + var generated_134$2 = generated$2.assertVariance; + var generated_135$2 = generated$2.assertVoidTypeAnnotation; + var generated_136$2 = generated$2.assertEnumDeclaration; + var generated_137$2 = generated$2.assertEnumBooleanBody; + var generated_138$2 = generated$2.assertEnumNumberBody; + var generated_139$2 = generated$2.assertEnumStringBody; + var generated_140$2 = generated$2.assertEnumSymbolBody; + var generated_141$2 = generated$2.assertEnumBooleanMember; + var generated_142$2 = generated$2.assertEnumNumberMember; + var generated_143$2 = generated$2.assertEnumStringMember; + var generated_144$2 = generated$2.assertEnumDefaultedMember; + var generated_145$2 = generated$2.assertJSXAttribute; + var generated_146$2 = generated$2.assertJSXClosingElement; + var generated_147$2 = generated$2.assertJSXElement; + var generated_148$2 = generated$2.assertJSXEmptyExpression; + var generated_149$2 = generated$2.assertJSXExpressionContainer; + var generated_150$2 = generated$2.assertJSXSpreadChild; + var generated_151$2 = generated$2.assertJSXIdentifier; + var generated_152$2 = generated$2.assertJSXMemberExpression; + var generated_153$2 = generated$2.assertJSXNamespacedName; + var generated_154$2 = generated$2.assertJSXOpeningElement; + var generated_155$2 = generated$2.assertJSXSpreadAttribute; + var generated_156$2 = generated$2.assertJSXText; + var generated_157$2 = generated$2.assertJSXFragment; + var generated_158$2 = generated$2.assertJSXOpeningFragment; + var generated_159$2 = generated$2.assertJSXClosingFragment; + var generated_160$2 = generated$2.assertNoop; + var generated_161$2 = generated$2.assertPlaceholder; + var generated_162$2 = generated$2.assertV8IntrinsicIdentifier; + var generated_163$2 = generated$2.assertArgumentPlaceholder; + var generated_164$2 = generated$2.assertBindExpression; + var generated_165$2 = generated$2.assertClassProperty; + var generated_166$2 = generated$2.assertPipelineTopicExpression; + var generated_167$2 = generated$2.assertPipelineBareFunction; + var generated_168$2 = generated$2.assertPipelinePrimaryTopicReference; + var generated_169$2 = generated$2.assertClassPrivateProperty; + var generated_170$2 = generated$2.assertClassPrivateMethod; + var generated_171$2 = generated$2.assertImportAttribute; + var generated_172$2 = generated$2.assertDecorator; + var generated_173$2 = generated$2.assertDoExpression; + var generated_174$2 = generated$2.assertExportDefaultSpecifier; + var generated_175$2 = generated$2.assertPrivateName; + var generated_176$2 = generated$2.assertRecordExpression; + var generated_177$2 = generated$2.assertTupleExpression; + var generated_178$2 = generated$2.assertDecimalLiteral; + var generated_179$2 = generated$2.assertStaticBlock; + var generated_180$2 = generated$2.assertTSParameterProperty; + var generated_181$2 = generated$2.assertTSDeclareFunction; + var generated_182$2 = generated$2.assertTSDeclareMethod; + var generated_183$2 = generated$2.assertTSQualifiedName; + var generated_184$2 = generated$2.assertTSCallSignatureDeclaration; + var generated_185$2 = generated$2.assertTSConstructSignatureDeclaration; + var generated_186$2 = generated$2.assertTSPropertySignature; + var generated_187$2 = generated$2.assertTSMethodSignature; + var generated_188$2 = generated$2.assertTSIndexSignature; + var generated_189$2 = generated$2.assertTSAnyKeyword; + var generated_190$2 = generated$2.assertTSBooleanKeyword; + var generated_191$2 = generated$2.assertTSBigIntKeyword; + var generated_192$2 = generated$2.assertTSIntrinsicKeyword; + var generated_193$2 = generated$2.assertTSNeverKeyword; + var generated_194$2 = generated$2.assertTSNullKeyword; + var generated_195$2 = generated$2.assertTSNumberKeyword; + var generated_196$2 = generated$2.assertTSObjectKeyword; + var generated_197$2 = generated$2.assertTSStringKeyword; + var generated_198$2 = generated$2.assertTSSymbolKeyword; + var generated_199$2 = generated$2.assertTSUndefinedKeyword; + var generated_200$2 = generated$2.assertTSUnknownKeyword; + var generated_201$2 = generated$2.assertTSVoidKeyword; + var generated_202$2 = generated$2.assertTSThisType; + var generated_203$2 = generated$2.assertTSFunctionType; + var generated_204$2 = generated$2.assertTSConstructorType; + var generated_205$2 = generated$2.assertTSTypeReference; + var generated_206$2 = generated$2.assertTSTypePredicate; + var generated_207$2 = generated$2.assertTSTypeQuery; + var generated_208$2 = generated$2.assertTSTypeLiteral; + var generated_209$2 = generated$2.assertTSArrayType; + var generated_210$2 = generated$2.assertTSTupleType; + var generated_211$2 = generated$2.assertTSOptionalType; + var generated_212$2 = generated$2.assertTSRestType; + var generated_213$2 = generated$2.assertTSNamedTupleMember; + var generated_214$2 = generated$2.assertTSUnionType; + var generated_215$2 = generated$2.assertTSIntersectionType; + var generated_216$2 = generated$2.assertTSConditionalType; + var generated_217$2 = generated$2.assertTSInferType; + var generated_218$2 = generated$2.assertTSParenthesizedType; + var generated_219$2 = generated$2.assertTSTypeOperator; + var generated_220$2 = generated$2.assertTSIndexedAccessType; + var generated_221$2 = generated$2.assertTSMappedType; + var generated_222$2 = generated$2.assertTSLiteralType; + var generated_223$2 = generated$2.assertTSExpressionWithTypeArguments; + var generated_224$2 = generated$2.assertTSInterfaceDeclaration; + var generated_225$2 = generated$2.assertTSInterfaceBody; + var generated_226$2 = generated$2.assertTSTypeAliasDeclaration; + var generated_227$2 = generated$2.assertTSAsExpression; + var generated_228$2 = generated$2.assertTSTypeAssertion; + var generated_229$2 = generated$2.assertTSEnumDeclaration; + var generated_230$2 = generated$2.assertTSEnumMember; + var generated_231$2 = generated$2.assertTSModuleDeclaration; + var generated_232$2 = generated$2.assertTSModuleBlock; + var generated_233$2 = generated$2.assertTSImportType; + var generated_234$2 = generated$2.assertTSImportEqualsDeclaration; + var generated_235$2 = generated$2.assertTSExternalModuleReference; + var generated_236$2 = generated$2.assertTSNonNullExpression; + var generated_237$2 = generated$2.assertTSExportAssignment; + var generated_238$2 = generated$2.assertTSNamespaceExportDeclaration; + var generated_239$2 = generated$2.assertTSTypeAnnotation; + var generated_240$2 = generated$2.assertTSTypeParameterInstantiation; + var generated_241$2 = generated$2.assertTSTypeParameterDeclaration; + var generated_242$2 = generated$2.assertTSTypeParameter; + var generated_243$2 = generated$2.assertExpression; + var generated_244$2 = generated$2.assertBinary; + var generated_245$2 = generated$2.assertScopable; + var generated_246$2 = generated$2.assertBlockParent; + var generated_247$2 = generated$2.assertBlock; + var generated_248$2 = generated$2.assertStatement; + var generated_249$2 = generated$2.assertTerminatorless; + var generated_250$2 = generated$2.assertCompletionStatement; + var generated_251$2 = generated$2.assertConditional; + var generated_252$2 = generated$2.assertLoop; + var generated_253$2 = generated$2.assertWhile; + var generated_254$2 = generated$2.assertExpressionWrapper; + var generated_255$2 = generated$2.assertFor; + var generated_256$2 = generated$2.assertForXStatement; + var generated_257$2 = generated$2.assertFunction; + var generated_258$2 = generated$2.assertFunctionParent; + var generated_259$2 = generated$2.assertPureish; + var generated_260$2 = generated$2.assertDeclaration; + var generated_261$2 = generated$2.assertPatternLike; + var generated_262$2 = generated$2.assertLVal; + var generated_263$2 = generated$2.assertTSEntityName; + var generated_264$2 = generated$2.assertLiteral; + var generated_265$2 = generated$2.assertImmutable; + var generated_266$2 = generated$2.assertUserWhitespacable; + var generated_267$2 = generated$2.assertMethod; + var generated_268$2 = generated$2.assertObjectMember; + var generated_269$2 = generated$2.assertProperty; + var generated_270$2 = generated$2.assertUnaryLike; + var generated_271$2 = generated$2.assertPattern; + var generated_272$2 = generated$2.assertClass; + var generated_273$2 = generated$2.assertModuleDeclaration; + var generated_274$2 = generated$2.assertExportDeclaration; + var generated_275$2 = generated$2.assertModuleSpecifier; + var generated_276$2 = generated$2.assertFlow; + var generated_277$2 = generated$2.assertFlowType; + var generated_278$2 = generated$2.assertFlowBaseAnnotation; + var generated_279$2 = generated$2.assertFlowDeclaration; + var generated_280$2 = generated$2.assertFlowPredicate; + var generated_281$2 = generated$2.assertEnumBody; + var generated_282$2 = generated$2.assertEnumMember; + var generated_283$2 = generated$2.assertJSX; + var generated_284$2 = generated$2.assertPrivate; + var generated_285$2 = generated$2.assertTSTypeElement; + var generated_286$2 = generated$2.assertTSType; + var generated_287$2 = generated$2.assertTSBaseType; + var generated_288$2 = generated$2.assertNumberLiteral; + var generated_289$2 = generated$2.assertRegexLiteral; + var generated_290$2 = generated$2.assertRestProperty; + var generated_291$2 = generated$2.assertSpreadProperty; + + var createTypeAnnotationBasedOnTypeof_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = createTypeAnnotationBasedOnTypeof; + + + + function createTypeAnnotationBasedOnTypeof(type) { + if (type === "string") { + return (0, generated$1.stringTypeAnnotation)(); + } else if (type === "number") { + return (0, generated$1.numberTypeAnnotation)(); + } else if (type === "undefined") { + return (0, generated$1.voidTypeAnnotation)(); + } else if (type === "boolean") { + return (0, generated$1.booleanTypeAnnotation)(); + } else if (type === "function") { + return (0, generated$1.genericTypeAnnotation)((0, generated$1.identifier)("Function")); + } else if (type === "object") { + return (0, generated$1.genericTypeAnnotation)((0, generated$1.identifier)("Object")); + } else if (type === "symbol") { + return (0, generated$1.genericTypeAnnotation)((0, generated$1.identifier)("Symbol")); + } else { + throw new Error("Invalid typeof value"); + } + } + }); + + unwrapExports(createTypeAnnotationBasedOnTypeof_1); + + var removeTypeDuplicates_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = removeTypeDuplicates; + + + + function removeTypeDuplicates(nodes) { + const generics = {}; + const bases = {}; + const typeGroups = []; + const types = []; + + for (let i = 0; i < nodes.length; i++) { + const node = nodes[i]; + if (!node) continue; + + if (types.indexOf(node) >= 0) { + continue; + } + + if ((0, generated.isAnyTypeAnnotation)(node)) { + return [node]; + } + + if ((0, generated.isFlowBaseAnnotation)(node)) { + bases[node.type] = node; + continue; + } + + if ((0, generated.isUnionTypeAnnotation)(node)) { + if (typeGroups.indexOf(node.types) < 0) { + nodes = nodes.concat(node.types); + typeGroups.push(node.types); + } + + continue; + } + + if ((0, generated.isGenericTypeAnnotation)(node)) { + const name = node.id.name; + + if (generics[name]) { + let existing = generics[name]; + + if (existing.typeParameters) { + if (node.typeParameters) { + existing.typeParameters.params = removeTypeDuplicates(existing.typeParameters.params.concat(node.typeParameters.params)); + } + } else { + existing = node.typeParameters; + } + } else { + generics[name] = node; + } + + continue; + } + + types.push(node); + } + + for (const type of Object.keys(bases)) { + types.push(bases[type]); + } + + for (const name of Object.keys(generics)) { + types.push(generics[name]); + } + + return types; + } + }); + + unwrapExports(removeTypeDuplicates_1); + + var createFlowUnionType_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = createFlowUnionType; + + + + var _removeTypeDuplicates = _interopRequireDefault(removeTypeDuplicates_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function createFlowUnionType(types) { + const flattened = (0, _removeTypeDuplicates.default)(types); + + if (flattened.length === 1) { + return flattened[0]; + } else { + return (0, generated$1.unionTypeAnnotation)(flattened); + } + } + }); + + unwrapExports(createFlowUnionType_1); + + var removeTypeDuplicates_1$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = removeTypeDuplicates; + + + + function removeTypeDuplicates(nodes) { + const generics = {}; + const bases = {}; + const typeGroups = []; + const types = []; + + for (let i = 0; i < nodes.length; i++) { + const node = nodes[i]; + if (!node) continue; + + if (types.indexOf(node) >= 0) { + continue; + } + + if ((0, generated.isTSAnyKeyword)(node.type)) { + return [node]; + } + + if ((0, generated.isTSBaseType)(node)) { + bases[node.type] = node; + continue; + } + + if ((0, generated.isTSUnionType)(node)) { + if (typeGroups.indexOf(node.types) < 0) { + nodes = nodes.concat(node.types); + typeGroups.push(node.types); + } + + continue; + } + + types.push(node); + } + + for (const type of Object.keys(bases)) { + types.push(bases[type]); + } + + for (const name of Object.keys(generics)) { + types.push(generics[name]); + } + + return types; + } + }); + + unwrapExports(removeTypeDuplicates_1$1); + + var createTSUnionType_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = createTSUnionType; + + + + var _removeTypeDuplicates = _interopRequireDefault(removeTypeDuplicates_1$1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function createTSUnionType(typeAnnotations) { + const types = typeAnnotations.map(type => type.typeAnnotations); + const flattened = (0, _removeTypeDuplicates.default)(types); + + if (flattened.length === 1) { + return flattened[0]; + } else { + return (0, generated$1.tsUnionType)(flattened); + } + } + }); + + unwrapExports(createTSUnionType_1); + + var cloneNode_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = cloneNode; + + + + const has = Function.call.bind(Object.prototype.hasOwnProperty); + + function cloneIfNode(obj, deep, withoutLoc) { + if (obj && typeof obj.type === "string") { + return cloneNode(obj, deep, withoutLoc); + } + + return obj; + } + + function cloneIfNodeOrArray(obj, deep, withoutLoc) { + if (Array.isArray(obj)) { + return obj.map(node => cloneIfNode(node, deep, withoutLoc)); + } + + return cloneIfNode(obj, deep, withoutLoc); + } + + function cloneNode(node, deep = true, withoutLoc = false) { + if (!node) return node; + const { + type + } = node; + const newNode = { + type + }; + + if (type === "Identifier") { + newNode.name = node.name; + + if (has(node, "optional") && typeof node.optional === "boolean") { + newNode.optional = node.optional; + } + + if (has(node, "typeAnnotation")) { + newNode.typeAnnotation = deep ? cloneIfNodeOrArray(node.typeAnnotation, true, withoutLoc) : node.typeAnnotation; + } + } else if (!has(definitions.NODE_FIELDS, type)) { + throw new Error(`Unknown node type: "${type}"`); + } else { + for (const field of Object.keys(definitions.NODE_FIELDS[type])) { + if (has(node, field)) { + if (deep) { + newNode[field] = type === "File" && field === "comments" ? maybeCloneComments(node.comments, deep, withoutLoc) : cloneIfNodeOrArray(node[field], true, withoutLoc); + } else { + newNode[field] = node[field]; + } + } + } + } + + if (has(node, "loc")) { + if (withoutLoc) { + newNode.loc = null; + } else { + newNode.loc = node.loc; + } + } + + if (has(node, "leadingComments")) { + newNode.leadingComments = maybeCloneComments(node.leadingComments, deep, withoutLoc); + } + + if (has(node, "innerComments")) { + newNode.innerComments = maybeCloneComments(node.innerComments, deep, withoutLoc); + } + + if (has(node, "trailingComments")) { + newNode.trailingComments = maybeCloneComments(node.trailingComments, deep, withoutLoc); + } + + if (has(node, "extra")) { + newNode.extra = Object.assign({}, node.extra); + } + + return newNode; + } + + function cloneCommentsWithoutLoc(comments) { + return comments.map(({ + type, + value + }) => ({ + type, + value, + loc: null + })); + } + + function maybeCloneComments(comments, deep, withoutLoc) { + return deep && withoutLoc ? cloneCommentsWithoutLoc(comments) : comments; + } + }); + + unwrapExports(cloneNode_1); + + var clone_1$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = clone; + + var _cloneNode = _interopRequireDefault(cloneNode_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function clone(node) { + return (0, _cloneNode.default)(node, false); + } + }); + + unwrapExports(clone_1$1); + + var cloneDeep_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = cloneDeep; + + var _cloneNode = _interopRequireDefault(cloneNode_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function cloneDeep(node) { + return (0, _cloneNode.default)(node); + } + }); + + unwrapExports(cloneDeep_1); + + var cloneDeepWithoutLoc_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = cloneDeepWithoutLoc; + + var _cloneNode = _interopRequireDefault(cloneNode_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function cloneDeepWithoutLoc(node) { + return (0, _cloneNode.default)(node, true, true); + } + }); + + unwrapExports(cloneDeepWithoutLoc_1); + + var cloneWithoutLoc_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = cloneWithoutLoc; + + var _cloneNode = _interopRequireDefault(cloneNode_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function cloneWithoutLoc(node) { + return (0, _cloneNode.default)(node, false, true); + } + }); + + unwrapExports(cloneWithoutLoc_1); + + var addComments_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = addComments; + + function addComments(node, type, comments) { + if (!comments || !node) return node; + const key = `${type}Comments`; + + if (node[key]) { + if (type === "leading") { + node[key] = comments.concat(node[key]); + } else { + node[key] = node[key].concat(comments); + } + } else { + node[key] = comments; + } + + return node; + } + }); + + unwrapExports(addComments_1); + + var addComment_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = addComment; + + var _addComments = _interopRequireDefault(addComments_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function addComment(node, type, content, line) { + return (0, _addComments.default)(node, type, [{ + type: line ? "CommentLine" : "CommentBlock", + value: content + }]); + } + }); + + unwrapExports(addComment_1); + + var inherit_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = inherit; + + function inherit(key, child, parent) { + if (child && parent) { + child[key] = Array.from(new Set([].concat(child[key], parent[key]).filter(Boolean))); + } + } + }); + + unwrapExports(inherit_1); + + var inheritInnerComments_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = inheritInnerComments; + + var _inherit = _interopRequireDefault(inherit_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function inheritInnerComments(child, parent) { + (0, _inherit.default)("innerComments", child, parent); + } + }); + + unwrapExports(inheritInnerComments_1); + + var inheritLeadingComments_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = inheritLeadingComments; + + var _inherit = _interopRequireDefault(inherit_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function inheritLeadingComments(child, parent) { + (0, _inherit.default)("leadingComments", child, parent); + } + }); + + unwrapExports(inheritLeadingComments_1); + + var inheritTrailingComments_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = inheritTrailingComments; + + var _inherit = _interopRequireDefault(inherit_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function inheritTrailingComments(child, parent) { + (0, _inherit.default)("trailingComments", child, parent); + } + }); + + unwrapExports(inheritTrailingComments_1); + + var inheritsComments_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = inheritsComments; + + var _inheritTrailingComments = _interopRequireDefault(inheritTrailingComments_1); + + var _inheritLeadingComments = _interopRequireDefault(inheritLeadingComments_1); + + var _inheritInnerComments = _interopRequireDefault(inheritInnerComments_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function inheritsComments(child, parent) { + (0, _inheritTrailingComments.default)(child, parent); + (0, _inheritLeadingComments.default)(child, parent); + (0, _inheritInnerComments.default)(child, parent); + return child; + } + }); + + unwrapExports(inheritsComments_1); + + var removeComments_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = removeComments; + + + + function removeComments(node) { + constants.COMMENT_KEYS.forEach(key => { + node[key] = null; + }); + + return node; + } + }); + + unwrapExports(removeComments_1); + + var generated$3 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.TSBASETYPE_TYPES = exports.TSTYPE_TYPES = exports.TSTYPEELEMENT_TYPES = exports.PRIVATE_TYPES = exports.JSX_TYPES = exports.ENUMMEMBER_TYPES = exports.ENUMBODY_TYPES = exports.FLOWPREDICATE_TYPES = exports.FLOWDECLARATION_TYPES = exports.FLOWBASEANNOTATION_TYPES = exports.FLOWTYPE_TYPES = exports.FLOW_TYPES = exports.MODULESPECIFIER_TYPES = exports.EXPORTDECLARATION_TYPES = exports.MODULEDECLARATION_TYPES = exports.CLASS_TYPES = exports.PATTERN_TYPES = exports.UNARYLIKE_TYPES = exports.PROPERTY_TYPES = exports.OBJECTMEMBER_TYPES = exports.METHOD_TYPES = exports.USERWHITESPACABLE_TYPES = exports.IMMUTABLE_TYPES = exports.LITERAL_TYPES = exports.TSENTITYNAME_TYPES = exports.LVAL_TYPES = exports.PATTERNLIKE_TYPES = exports.DECLARATION_TYPES = exports.PUREISH_TYPES = exports.FUNCTIONPARENT_TYPES = exports.FUNCTION_TYPES = exports.FORXSTATEMENT_TYPES = exports.FOR_TYPES = exports.EXPRESSIONWRAPPER_TYPES = exports.WHILE_TYPES = exports.LOOP_TYPES = exports.CONDITIONAL_TYPES = exports.COMPLETIONSTATEMENT_TYPES = exports.TERMINATORLESS_TYPES = exports.STATEMENT_TYPES = exports.BLOCK_TYPES = exports.BLOCKPARENT_TYPES = exports.SCOPABLE_TYPES = exports.BINARY_TYPES = exports.EXPRESSION_TYPES = void 0; + + + + const EXPRESSION_TYPES = definitions.FLIPPED_ALIAS_KEYS["Expression"]; + exports.EXPRESSION_TYPES = EXPRESSION_TYPES; + const BINARY_TYPES = definitions.FLIPPED_ALIAS_KEYS["Binary"]; + exports.BINARY_TYPES = BINARY_TYPES; + const SCOPABLE_TYPES = definitions.FLIPPED_ALIAS_KEYS["Scopable"]; + exports.SCOPABLE_TYPES = SCOPABLE_TYPES; + const BLOCKPARENT_TYPES = definitions.FLIPPED_ALIAS_KEYS["BlockParent"]; + exports.BLOCKPARENT_TYPES = BLOCKPARENT_TYPES; + const BLOCK_TYPES = definitions.FLIPPED_ALIAS_KEYS["Block"]; + exports.BLOCK_TYPES = BLOCK_TYPES; + const STATEMENT_TYPES = definitions.FLIPPED_ALIAS_KEYS["Statement"]; + exports.STATEMENT_TYPES = STATEMENT_TYPES; + const TERMINATORLESS_TYPES = definitions.FLIPPED_ALIAS_KEYS["Terminatorless"]; + exports.TERMINATORLESS_TYPES = TERMINATORLESS_TYPES; + const COMPLETIONSTATEMENT_TYPES = definitions.FLIPPED_ALIAS_KEYS["CompletionStatement"]; + exports.COMPLETIONSTATEMENT_TYPES = COMPLETIONSTATEMENT_TYPES; + const CONDITIONAL_TYPES = definitions.FLIPPED_ALIAS_KEYS["Conditional"]; + exports.CONDITIONAL_TYPES = CONDITIONAL_TYPES; + const LOOP_TYPES = definitions.FLIPPED_ALIAS_KEYS["Loop"]; + exports.LOOP_TYPES = LOOP_TYPES; + const WHILE_TYPES = definitions.FLIPPED_ALIAS_KEYS["While"]; + exports.WHILE_TYPES = WHILE_TYPES; + const EXPRESSIONWRAPPER_TYPES = definitions.FLIPPED_ALIAS_KEYS["ExpressionWrapper"]; + exports.EXPRESSIONWRAPPER_TYPES = EXPRESSIONWRAPPER_TYPES; + const FOR_TYPES = definitions.FLIPPED_ALIAS_KEYS["For"]; + exports.FOR_TYPES = FOR_TYPES; + const FORXSTATEMENT_TYPES = definitions.FLIPPED_ALIAS_KEYS["ForXStatement"]; + exports.FORXSTATEMENT_TYPES = FORXSTATEMENT_TYPES; + const FUNCTION_TYPES = definitions.FLIPPED_ALIAS_KEYS["Function"]; + exports.FUNCTION_TYPES = FUNCTION_TYPES; + const FUNCTIONPARENT_TYPES = definitions.FLIPPED_ALIAS_KEYS["FunctionParent"]; + exports.FUNCTIONPARENT_TYPES = FUNCTIONPARENT_TYPES; + const PUREISH_TYPES = definitions.FLIPPED_ALIAS_KEYS["Pureish"]; + exports.PUREISH_TYPES = PUREISH_TYPES; + const DECLARATION_TYPES = definitions.FLIPPED_ALIAS_KEYS["Declaration"]; + exports.DECLARATION_TYPES = DECLARATION_TYPES; + const PATTERNLIKE_TYPES = definitions.FLIPPED_ALIAS_KEYS["PatternLike"]; + exports.PATTERNLIKE_TYPES = PATTERNLIKE_TYPES; + const LVAL_TYPES = definitions.FLIPPED_ALIAS_KEYS["LVal"]; + exports.LVAL_TYPES = LVAL_TYPES; + const TSENTITYNAME_TYPES = definitions.FLIPPED_ALIAS_KEYS["TSEntityName"]; + exports.TSENTITYNAME_TYPES = TSENTITYNAME_TYPES; + const LITERAL_TYPES = definitions.FLIPPED_ALIAS_KEYS["Literal"]; + exports.LITERAL_TYPES = LITERAL_TYPES; + const IMMUTABLE_TYPES = definitions.FLIPPED_ALIAS_KEYS["Immutable"]; + exports.IMMUTABLE_TYPES = IMMUTABLE_TYPES; + const USERWHITESPACABLE_TYPES = definitions.FLIPPED_ALIAS_KEYS["UserWhitespacable"]; + exports.USERWHITESPACABLE_TYPES = USERWHITESPACABLE_TYPES; + const METHOD_TYPES = definitions.FLIPPED_ALIAS_KEYS["Method"]; + exports.METHOD_TYPES = METHOD_TYPES; + const OBJECTMEMBER_TYPES = definitions.FLIPPED_ALIAS_KEYS["ObjectMember"]; + exports.OBJECTMEMBER_TYPES = OBJECTMEMBER_TYPES; + const PROPERTY_TYPES = definitions.FLIPPED_ALIAS_KEYS["Property"]; + exports.PROPERTY_TYPES = PROPERTY_TYPES; + const UNARYLIKE_TYPES = definitions.FLIPPED_ALIAS_KEYS["UnaryLike"]; + exports.UNARYLIKE_TYPES = UNARYLIKE_TYPES; + const PATTERN_TYPES = definitions.FLIPPED_ALIAS_KEYS["Pattern"]; + exports.PATTERN_TYPES = PATTERN_TYPES; + const CLASS_TYPES = definitions.FLIPPED_ALIAS_KEYS["Class"]; + exports.CLASS_TYPES = CLASS_TYPES; + const MODULEDECLARATION_TYPES = definitions.FLIPPED_ALIAS_KEYS["ModuleDeclaration"]; + exports.MODULEDECLARATION_TYPES = MODULEDECLARATION_TYPES; + const EXPORTDECLARATION_TYPES = definitions.FLIPPED_ALIAS_KEYS["ExportDeclaration"]; + exports.EXPORTDECLARATION_TYPES = EXPORTDECLARATION_TYPES; + const MODULESPECIFIER_TYPES = definitions.FLIPPED_ALIAS_KEYS["ModuleSpecifier"]; + exports.MODULESPECIFIER_TYPES = MODULESPECIFIER_TYPES; + const FLOW_TYPES = definitions.FLIPPED_ALIAS_KEYS["Flow"]; + exports.FLOW_TYPES = FLOW_TYPES; + const FLOWTYPE_TYPES = definitions.FLIPPED_ALIAS_KEYS["FlowType"]; + exports.FLOWTYPE_TYPES = FLOWTYPE_TYPES; + const FLOWBASEANNOTATION_TYPES = definitions.FLIPPED_ALIAS_KEYS["FlowBaseAnnotation"]; + exports.FLOWBASEANNOTATION_TYPES = FLOWBASEANNOTATION_TYPES; + const FLOWDECLARATION_TYPES = definitions.FLIPPED_ALIAS_KEYS["FlowDeclaration"]; + exports.FLOWDECLARATION_TYPES = FLOWDECLARATION_TYPES; + const FLOWPREDICATE_TYPES = definitions.FLIPPED_ALIAS_KEYS["FlowPredicate"]; + exports.FLOWPREDICATE_TYPES = FLOWPREDICATE_TYPES; + const ENUMBODY_TYPES = definitions.FLIPPED_ALIAS_KEYS["EnumBody"]; + exports.ENUMBODY_TYPES = ENUMBODY_TYPES; + const ENUMMEMBER_TYPES = definitions.FLIPPED_ALIAS_KEYS["EnumMember"]; + exports.ENUMMEMBER_TYPES = ENUMMEMBER_TYPES; + const JSX_TYPES = definitions.FLIPPED_ALIAS_KEYS["JSX"]; + exports.JSX_TYPES = JSX_TYPES; + const PRIVATE_TYPES = definitions.FLIPPED_ALIAS_KEYS["Private"]; + exports.PRIVATE_TYPES = PRIVATE_TYPES; + const TSTYPEELEMENT_TYPES = definitions.FLIPPED_ALIAS_KEYS["TSTypeElement"]; + exports.TSTYPEELEMENT_TYPES = TSTYPEELEMENT_TYPES; + const TSTYPE_TYPES = definitions.FLIPPED_ALIAS_KEYS["TSType"]; + exports.TSTYPE_TYPES = TSTYPE_TYPES; + const TSBASETYPE_TYPES = definitions.FLIPPED_ALIAS_KEYS["TSBaseType"]; + exports.TSBASETYPE_TYPES = TSBASETYPE_TYPES; + }); + + unwrapExports(generated$3); + var generated_1$3 = generated$3.TSBASETYPE_TYPES; + var generated_2$3 = generated$3.TSTYPE_TYPES; + var generated_3$3 = generated$3.TSTYPEELEMENT_TYPES; + var generated_4$3 = generated$3.PRIVATE_TYPES; + var generated_5$3 = generated$3.JSX_TYPES; + var generated_6$3 = generated$3.ENUMMEMBER_TYPES; + var generated_7$3 = generated$3.ENUMBODY_TYPES; + var generated_8$3 = generated$3.FLOWPREDICATE_TYPES; + var generated_9$3 = generated$3.FLOWDECLARATION_TYPES; + var generated_10$3 = generated$3.FLOWBASEANNOTATION_TYPES; + var generated_11$3 = generated$3.FLOWTYPE_TYPES; + var generated_12$3 = generated$3.FLOW_TYPES; + var generated_13$3 = generated$3.MODULESPECIFIER_TYPES; + var generated_14$3 = generated$3.EXPORTDECLARATION_TYPES; + var generated_15$3 = generated$3.MODULEDECLARATION_TYPES; + var generated_16$3 = generated$3.CLASS_TYPES; + var generated_17$3 = generated$3.PATTERN_TYPES; + var generated_18$3 = generated$3.UNARYLIKE_TYPES; + var generated_19$3 = generated$3.PROPERTY_TYPES; + var generated_20$3 = generated$3.OBJECTMEMBER_TYPES; + var generated_21$3 = generated$3.METHOD_TYPES; + var generated_22$3 = generated$3.USERWHITESPACABLE_TYPES; + var generated_23$3 = generated$3.IMMUTABLE_TYPES; + var generated_24$3 = generated$3.LITERAL_TYPES; + var generated_25$3 = generated$3.TSENTITYNAME_TYPES; + var generated_26$3 = generated$3.LVAL_TYPES; + var generated_27$3 = generated$3.PATTERNLIKE_TYPES; + var generated_28$3 = generated$3.DECLARATION_TYPES; + var generated_29$3 = generated$3.PUREISH_TYPES; + var generated_30$3 = generated$3.FUNCTIONPARENT_TYPES; + var generated_31$3 = generated$3.FUNCTION_TYPES; + var generated_32$3 = generated$3.FORXSTATEMENT_TYPES; + var generated_33$3 = generated$3.FOR_TYPES; + var generated_34$3 = generated$3.EXPRESSIONWRAPPER_TYPES; + var generated_35$3 = generated$3.WHILE_TYPES; + var generated_36$3 = generated$3.LOOP_TYPES; + var generated_37$3 = generated$3.CONDITIONAL_TYPES; + var generated_38$3 = generated$3.COMPLETIONSTATEMENT_TYPES; + var generated_39$3 = generated$3.TERMINATORLESS_TYPES; + var generated_40$3 = generated$3.STATEMENT_TYPES; + var generated_41$3 = generated$3.BLOCK_TYPES; + var generated_42$3 = generated$3.BLOCKPARENT_TYPES; + var generated_43$3 = generated$3.SCOPABLE_TYPES; + var generated_44$3 = generated$3.BINARY_TYPES; + var generated_45$3 = generated$3.EXPRESSION_TYPES; + + var toBlock_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = toBlock; + + + + + + function toBlock(node, parent) { + if ((0, generated.isBlockStatement)(node)) { + return node; + } + + let blockNodes = []; + + if ((0, generated.isEmptyStatement)(node)) { + blockNodes = []; + } else { + if (!(0, generated.isStatement)(node)) { + if ((0, generated.isFunction)(parent)) { + node = (0, generated$1.returnStatement)(node); + } else { + node = (0, generated$1.expressionStatement)(node); + } + } + + blockNodes = [node]; + } + + return (0, generated$1.blockStatement)(blockNodes); + } + }); + + unwrapExports(toBlock_1); + + var ensureBlock_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = ensureBlock; + + var _toBlock = _interopRequireDefault(toBlock_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function ensureBlock(node, key = "body") { + return node[key] = (0, _toBlock.default)(node[key], node); + } + }); + + unwrapExports(ensureBlock_1); + + var toIdentifier_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = toIdentifier; + + var _isValidIdentifier = _interopRequireDefault(isValidIdentifier_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function toIdentifier(name) { + name = name + ""; + name = name.replace(/[^a-zA-Z0-9$_]/g, "-"); + name = name.replace(/^[-0-9]+/, ""); + name = name.replace(/[-\s]+(.)?/g, function (match, c) { + return c ? c.toUpperCase() : ""; + }); + + if (!(0, _isValidIdentifier.default)(name)) { + name = `_${name}`; + } + + return name || "_"; + } + }); + + unwrapExports(toIdentifier_1); + + var toBindingIdentifierName_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = toBindingIdentifierName; + + var _toIdentifier = _interopRequireDefault(toIdentifier_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function toBindingIdentifierName(name) { + name = (0, _toIdentifier.default)(name); + if (name === "eval" || name === "arguments") name = "_" + name; + return name; + } + }); + + unwrapExports(toBindingIdentifierName_1); + + var toComputedKey_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = toComputedKey; + + + + + + function toComputedKey(node, key = node.key || node.property) { + if (!node.computed && (0, generated.isIdentifier)(key)) key = (0, generated$1.stringLiteral)(key.name); + return key; + } + }); + + unwrapExports(toComputedKey_1); + + var toExpression_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = toExpression; + + + + function toExpression(node) { + if ((0, generated.isExpressionStatement)(node)) { + node = node.expression; + } + + if ((0, generated.isExpression)(node)) { + return node; + } + + if ((0, generated.isClass)(node)) { + node.type = "ClassExpression"; + } else if ((0, generated.isFunction)(node)) { + node.type = "FunctionExpression"; + } + + if (!(0, generated.isExpression)(node)) { + throw new Error(`cannot turn ${node.type} to an expression`); + } + + return node; + } + }); + + unwrapExports(toExpression_1); + + var traverseFast_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = traverseFast; + + + + function traverseFast(node, enter, opts) { + if (!node) return; + const keys = definitions.VISITOR_KEYS[node.type]; + if (!keys) return; + opts = opts || {}; + enter(node, opts); + + for (const key of keys) { + const subNode = node[key]; + + if (Array.isArray(subNode)) { + for (const node of subNode) { + traverseFast(node, enter, opts); + } + } else { + traverseFast(subNode, enter, opts); + } + } + } + }); + + unwrapExports(traverseFast_1); + + var removeProperties_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = removeProperties; + + + + const CLEAR_KEYS = ["tokens", "start", "end", "loc", "raw", "rawValue"]; + + const CLEAR_KEYS_PLUS_COMMENTS = constants.COMMENT_KEYS.concat(["comments"]).concat(CLEAR_KEYS); + + function removeProperties(node, opts = {}) { + const map = opts.preserveComments ? CLEAR_KEYS : CLEAR_KEYS_PLUS_COMMENTS; + + for (const key of map) { + if (node[key] != null) node[key] = undefined; + } + + for (const key of Object.keys(node)) { + if (key[0] === "_" && node[key] != null) node[key] = undefined; + } + + const symbols = Object.getOwnPropertySymbols(node); + + for (const sym of symbols) { + node[sym] = null; + } + } + }); + + unwrapExports(removeProperties_1); + + var removePropertiesDeep_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = removePropertiesDeep; + + var _traverseFast = _interopRequireDefault(traverseFast_1); + + var _removeProperties = _interopRequireDefault(removeProperties_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function removePropertiesDeep(tree, opts) { + (0, _traverseFast.default)(tree, _removeProperties.default, opts); + return tree; + } + }); + + unwrapExports(removePropertiesDeep_1); + + var toKeyAlias_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = toKeyAlias; + + + + var _cloneNode = _interopRequireDefault(cloneNode_1); + + var _removePropertiesDeep = _interopRequireDefault(removePropertiesDeep_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function toKeyAlias(node, key = node.key) { + let alias; + + if (node.kind === "method") { + return toKeyAlias.increment() + ""; + } else if ((0, generated.isIdentifier)(key)) { + alias = key.name; + } else if ((0, generated.isStringLiteral)(key)) { + alias = JSON.stringify(key.value); + } else { + alias = JSON.stringify((0, _removePropertiesDeep.default)((0, _cloneNode.default)(key))); + } + + if (node.computed) { + alias = `[${alias}]`; + } + + if (node.static) { + alias = `static:${alias}`; + } + + return alias; + } + + toKeyAlias.uid = 0; + + toKeyAlias.increment = function () { + if (toKeyAlias.uid >= Number.MAX_SAFE_INTEGER) { + return toKeyAlias.uid = 0; + } else { + return toKeyAlias.uid++; + } + }; + }); + + unwrapExports(toKeyAlias_1); + + var getBindingIdentifiers_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = getBindingIdentifiers; + + + + function getBindingIdentifiers(node, duplicates, outerOnly) { + let search = [].concat(node); + const ids = Object.create(null); + + while (search.length) { + const id = search.shift(); + if (!id) continue; + const keys = getBindingIdentifiers.keys[id.type]; + + if ((0, generated.isIdentifier)(id)) { + if (duplicates) { + const _ids = ids[id.name] = ids[id.name] || []; + + _ids.push(id); + } else { + ids[id.name] = id; + } + + continue; + } + + if ((0, generated.isExportDeclaration)(id)) { + if ((0, generated.isDeclaration)(id.declaration)) { + search.push(id.declaration); + } + + continue; + } + + if (outerOnly) { + if ((0, generated.isFunctionDeclaration)(id)) { + search.push(id.id); + continue; + } + + if ((0, generated.isFunctionExpression)(id)) { + continue; + } + } + + if (keys) { + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + + if (id[key]) { + search = search.concat(id[key]); + } + } + } + } + + return ids; + } + + getBindingIdentifiers.keys = { + DeclareClass: ["id"], + DeclareFunction: ["id"], + DeclareModule: ["id"], + DeclareVariable: ["id"], + DeclareInterface: ["id"], + DeclareTypeAlias: ["id"], + DeclareOpaqueType: ["id"], + InterfaceDeclaration: ["id"], + TypeAlias: ["id"], + OpaqueType: ["id"], + CatchClause: ["param"], + LabeledStatement: ["label"], + UnaryExpression: ["argument"], + AssignmentExpression: ["left"], + ImportSpecifier: ["local"], + ImportNamespaceSpecifier: ["local"], + ImportDefaultSpecifier: ["local"], + ImportDeclaration: ["specifiers"], + ExportSpecifier: ["exported"], + ExportNamespaceSpecifier: ["exported"], + ExportDefaultSpecifier: ["exported"], + FunctionDeclaration: ["id", "params"], + FunctionExpression: ["id", "params"], + ArrowFunctionExpression: ["params"], + ObjectMethod: ["params"], + ClassMethod: ["params"], + ForInStatement: ["left"], + ForOfStatement: ["left"], + ClassDeclaration: ["id"], + ClassExpression: ["id"], + RestElement: ["argument"], + UpdateExpression: ["argument"], + ObjectProperty: ["value"], + AssignmentPattern: ["left"], + ArrayPattern: ["elements"], + ObjectPattern: ["properties"], + VariableDeclaration: ["declarations"], + VariableDeclarator: ["id"] + }; + }); + + unwrapExports(getBindingIdentifiers_1); + + var gatherSequenceExpressions_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = gatherSequenceExpressions; + + var _getBindingIdentifiers = _interopRequireDefault(getBindingIdentifiers_1); + + + + + + var _cloneNode = _interopRequireDefault(cloneNode_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function gatherSequenceExpressions(nodes, scope, declars) { + const exprs = []; + let ensureLastUndefined = true; + + for (const node of nodes) { + if (!(0, generated.isEmptyStatement)(node)) { + ensureLastUndefined = false; + } + + if ((0, generated.isExpression)(node)) { + exprs.push(node); + } else if ((0, generated.isExpressionStatement)(node)) { + exprs.push(node.expression); + } else if ((0, generated.isVariableDeclaration)(node)) { + if (node.kind !== "var") return; + + for (const declar of node.declarations) { + const bindings = (0, _getBindingIdentifiers.default)(declar); + + for (const key of Object.keys(bindings)) { + declars.push({ + kind: node.kind, + id: (0, _cloneNode.default)(bindings[key]) + }); + } + + if (declar.init) { + exprs.push((0, generated$1.assignmentExpression)("=", declar.id, declar.init)); + } + } + + ensureLastUndefined = true; + } else if ((0, generated.isIfStatement)(node)) { + const consequent = node.consequent ? gatherSequenceExpressions([node.consequent], scope, declars) : scope.buildUndefinedNode(); + const alternate = node.alternate ? gatherSequenceExpressions([node.alternate], scope, declars) : scope.buildUndefinedNode(); + if (!consequent || !alternate) return; + exprs.push((0, generated$1.conditionalExpression)(node.test, consequent, alternate)); + } else if ((0, generated.isBlockStatement)(node)) { + const body = gatherSequenceExpressions(node.body, scope, declars); + if (!body) return; + exprs.push(body); + } else if ((0, generated.isEmptyStatement)(node)) { + if (nodes.indexOf(node) === 0) { + ensureLastUndefined = true; + } + } else { + return; + } + } + + if (ensureLastUndefined) { + exprs.push(scope.buildUndefinedNode()); + } + + if (exprs.length === 1) { + return exprs[0]; + } else { + return (0, generated$1.sequenceExpression)(exprs); + } + } + }); + + unwrapExports(gatherSequenceExpressions_1); + + var toSequenceExpression_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = toSequenceExpression; + + var _gatherSequenceExpressions = _interopRequireDefault(gatherSequenceExpressions_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function toSequenceExpression(nodes, scope) { + if (!(nodes == null ? void 0 : nodes.length)) return; + const declars = []; + const result = (0, _gatherSequenceExpressions.default)(nodes, scope, declars); + if (!result) return; + + for (const declar of declars) { + scope.push(declar); + } + + return result; + } + }); + + unwrapExports(toSequenceExpression_1); + + var toStatement_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = toStatement; + + + + + + function toStatement(node, ignore) { + if ((0, generated.isStatement)(node)) { + return node; + } + + let mustHaveId = false; + let newType; + + if ((0, generated.isClass)(node)) { + mustHaveId = true; + newType = "ClassDeclaration"; + } else if ((0, generated.isFunction)(node)) { + mustHaveId = true; + newType = "FunctionDeclaration"; + } else if ((0, generated.isAssignmentExpression)(node)) { + return (0, generated$1.expressionStatement)(node); + } + + if (mustHaveId && !node.id) { + newType = false; + } + + if (!newType) { + if (ignore) { + return false; + } else { + throw new Error(`cannot turn ${node.type} to a statement`); + } + } + + node.type = newType; + return node; + } + }); + + unwrapExports(toStatement_1); + + /** `Object#toString` result references. */ + var objectTag$3 = '[object Object]'; + + /** Used for built-in method references. */ + var funcProto$2 = Function.prototype, + objectProto$d = Object.prototype; + + /** Used to resolve the decompiled source of functions. */ + var funcToString$2 = funcProto$2.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty$a = objectProto$d.hasOwnProperty; + + /** Used to infer the `Object` constructor. */ + var objectCtorString = funcToString$2.call(Object); + + /** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + function isPlainObject(value) { + if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$3) { + return false; + } + var proto = _getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty$a.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString$2.call(Ctor) == objectCtorString; + } + + var isPlainObject_1 = isPlainObject; + + /** `Object#toString` result references. */ + var regexpTag$3 = '[object RegExp]'; + + /** + * The base implementation of `_.isRegExp` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + */ + function baseIsRegExp(value) { + return isObjectLike_1(value) && _baseGetTag(value) == regexpTag$3; + } + + var _baseIsRegExp = baseIsRegExp; + + /* Node.js helper references. */ + var nodeIsRegExp = _nodeUtil && _nodeUtil.isRegExp; + + /** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ + var isRegExp = nodeIsRegExp ? _baseUnary(nodeIsRegExp) : _baseIsRegExp; + + var isRegExp_1 = isRegExp; + + var valueToNode_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = valueToNode; + + var _isPlainObject = _interopRequireDefault(isPlainObject_1); + + var _isRegExp = _interopRequireDefault(isRegExp_1); + + var _isValidIdentifier = _interopRequireDefault(isValidIdentifier_1); + + + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function valueToNode(value) { + if (value === undefined) { + return (0, generated$1.identifier)("undefined"); + } + + if (value === true || value === false) { + return (0, generated$1.booleanLiteral)(value); + } + + if (value === null) { + return (0, generated$1.nullLiteral)(); + } + + if (typeof value === "string") { + return (0, generated$1.stringLiteral)(value); + } + + if (typeof value === "number") { + let result; + + if (Number.isFinite(value)) { + result = (0, generated$1.numericLiteral)(Math.abs(value)); + } else { + let numerator; + + if (Number.isNaN(value)) { + numerator = (0, generated$1.numericLiteral)(0); + } else { + numerator = (0, generated$1.numericLiteral)(1); + } + + result = (0, generated$1.binaryExpression)("/", numerator, (0, generated$1.numericLiteral)(0)); + } + + if (value < 0 || Object.is(value, -0)) { + result = (0, generated$1.unaryExpression)("-", result); + } + + return result; + } + + if ((0, _isRegExp.default)(value)) { + const pattern = value.source; + const flags = value.toString().match(/\/([a-z]+|)$/)[1]; + return (0, generated$1.regExpLiteral)(pattern, flags); + } + + if (Array.isArray(value)) { + return (0, generated$1.arrayExpression)(value.map(valueToNode)); + } + + if ((0, _isPlainObject.default)(value)) { + const props = []; + + for (const key of Object.keys(value)) { + let nodeKey; + + if ((0, _isValidIdentifier.default)(key)) { + nodeKey = (0, generated$1.identifier)(key); + } else { + nodeKey = (0, generated$1.stringLiteral)(key); + } + + props.push((0, generated$1.objectProperty)(nodeKey, valueToNode(value[key]))); + } + + return (0, generated$1.objectExpression)(props); + } + + throw new Error("don't know how to turn this value into a node"); + } + }); + + unwrapExports(valueToNode_1); + + var appendToMemberExpression_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = appendToMemberExpression; + + + + function appendToMemberExpression(member, append, computed = false) { + member.object = (0, generated$1.memberExpression)(member.object, member.property, member.computed); + member.property = append; + member.computed = !!computed; + return member; + } + }); + + unwrapExports(appendToMemberExpression_1); + + var inherits_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = inherits; + + + + var _inheritsComments = _interopRequireDefault(inheritsComments_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function inherits(child, parent) { + if (!child || !parent) return child; + + for (const key of constants.INHERIT_KEYS.optional) { + if (child[key] == null) { + child[key] = parent[key]; + } + } + + for (const key of Object.keys(parent)) { + if (key[0] === "_" && key !== "__clone") child[key] = parent[key]; + } + + for (const key of constants.INHERIT_KEYS.force) { + child[key] = parent[key]; + } + + (0, _inheritsComments.default)(child, parent); + return child; + } + }); + + unwrapExports(inherits_1); + + var prependToMemberExpression_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = prependToMemberExpression; + + + + function prependToMemberExpression(member, prepend) { + member.object = (0, generated$1.memberExpression)(prepend, member.object); + return member; + } + }); + + unwrapExports(prependToMemberExpression_1); + + var getOuterBindingIdentifiers_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = getOuterBindingIdentifiers; + + var _getBindingIdentifiers = _interopRequireDefault(getBindingIdentifiers_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function getOuterBindingIdentifiers(node, duplicates) { + return (0, _getBindingIdentifiers.default)(node, duplicates, true); + } + }); + + unwrapExports(getOuterBindingIdentifiers_1); + + var traverse_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = traverse; + + + + function traverse(node, handlers, state) { + if (typeof handlers === "function") { + handlers = { + enter: handlers + }; + } + + const { + enter, + exit + } = handlers; + traverseSimpleImpl(node, enter, exit, state, []); + } + + function traverseSimpleImpl(node, enter, exit, state, ancestors) { + const keys = definitions.VISITOR_KEYS[node.type]; + if (!keys) return; + if (enter) enter(node, ancestors, state); + + for (const key of keys) { + const subNode = node[key]; + + if (Array.isArray(subNode)) { + for (let i = 0; i < subNode.length; i++) { + const child = subNode[i]; + if (!child) continue; + ancestors.push({ + node, + key, + index: i + }); + traverseSimpleImpl(child, enter, exit, state, ancestors); + ancestors.pop(); + } + } else if (subNode) { + ancestors.push({ + node, + key + }); + traverseSimpleImpl(subNode, enter, exit, state, ancestors); + ancestors.pop(); + } + } + + if (exit) exit(node, ancestors, state); + } + }); + + unwrapExports(traverse_1); + + var isBinding_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = isBinding; + + var _getBindingIdentifiers = _interopRequireDefault(getBindingIdentifiers_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function isBinding(node, parent, grandparent) { + if (grandparent && node.type === "Identifier" && parent.type === "ObjectProperty" && grandparent.type === "ObjectExpression") { + return false; + } + + const keys = _getBindingIdentifiers.default.keys[parent.type]; + + if (keys) { + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const val = parent[key]; + + if (Array.isArray(val)) { + if (val.indexOf(node) >= 0) return true; + } else { + if (val === node) return true; + } + } + } + + return false; + } + }); + + unwrapExports(isBinding_1); + + var isLet_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = isLet; + + + + + + function isLet(node) { + return (0, generated.isVariableDeclaration)(node) && (node.kind !== "var" || node[constants.BLOCK_SCOPED_SYMBOL]); + } + }); + + unwrapExports(isLet_1); + + var isBlockScoped_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = isBlockScoped; + + + + var _isLet = _interopRequireDefault(isLet_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function isBlockScoped(node) { + return (0, generated.isFunctionDeclaration)(node) || (0, generated.isClassDeclaration)(node) || (0, _isLet.default)(node); + } + }); + + unwrapExports(isBlockScoped_1); + + var isImmutable_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = isImmutable; + + var _isType = _interopRequireDefault(isType_1); + + + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function isImmutable(node) { + if ((0, _isType.default)(node.type, "Immutable")) return true; + + if ((0, generated.isIdentifier)(node)) { + if (node.name === "undefined") { + return true; + } else { + return false; + } + } + + return false; + } + }); + + unwrapExports(isImmutable_1); + + var isNodesEquivalent_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = isNodesEquivalent; + + + + function isNodesEquivalent(a, b) { + if (typeof a !== "object" || typeof b !== "object" || a == null || b == null) { + return a === b; + } + + if (a.type !== b.type) { + return false; + } + + const fields = Object.keys(definitions.NODE_FIELDS[a.type] || a.type); + const visitorKeys = definitions.VISITOR_KEYS[a.type]; + + for (const field of fields) { + if (typeof a[field] !== typeof b[field]) { + return false; + } + + if (a[field] == null && b[field] == null) { + continue; + } else if (a[field] == null || b[field] == null) { + return false; + } + + if (Array.isArray(a[field])) { + if (!Array.isArray(b[field])) { + return false; + } + + if (a[field].length !== b[field].length) { + return false; + } + + for (let i = 0; i < a[field].length; i++) { + if (!isNodesEquivalent(a[field][i], b[field][i])) { + return false; + } + } + + continue; + } + + if (typeof a[field] === "object" && !(visitorKeys == null ? void 0 : visitorKeys.includes(field))) { + for (const key of Object.keys(a[field])) { + if (a[field][key] !== b[field][key]) { + return false; + } + } + + continue; + } + + if (!isNodesEquivalent(a[field], b[field])) { + return false; + } + } + + return true; + } + }); + + unwrapExports(isNodesEquivalent_1); + + var isReferenced_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = isReferenced; + + function isReferenced(node, parent, grandparent) { + switch (parent.type) { + case "MemberExpression": + case "JSXMemberExpression": + case "OptionalMemberExpression": + if (parent.property === node) { + return !!parent.computed; + } + + return parent.object === node; + + case "VariableDeclarator": + return parent.init === node; + + case "ArrowFunctionExpression": + return parent.body === node; + + case "ExportSpecifier": + if (parent.source) { + return false; + } + + return parent.local === node; + + case "PrivateName": + return false; + + case "ClassMethod": + case "ClassPrivateMethod": + case "ObjectMethod": + if (parent.params.includes(node)) { + return false; + } + + case "ObjectProperty": + case "ClassProperty": + case "ClassPrivateProperty": + if (parent.key === node) { + return !!parent.computed; + } + + if (parent.value === node) { + return !grandparent || grandparent.type !== "ObjectPattern"; + } + + return true; + + case "ClassDeclaration": + case "ClassExpression": + return parent.superClass === node; + + case "AssignmentExpression": + return parent.right === node; + + case "AssignmentPattern": + return parent.right === node; + + case "LabeledStatement": + return false; + + case "CatchClause": + return false; + + case "RestElement": + return false; + + case "BreakStatement": + case "ContinueStatement": + return false; + + case "FunctionDeclaration": + case "FunctionExpression": + return false; + + case "ExportNamespaceSpecifier": + case "ExportDefaultSpecifier": + return false; + + case "ImportDefaultSpecifier": + case "ImportNamespaceSpecifier": + case "ImportSpecifier": + return false; + + case "JSXAttribute": + return false; + + case "ObjectPattern": + case "ArrayPattern": + return false; + + case "MetaProperty": + return false; + + case "ObjectTypeProperty": + return parent.key !== node; + + case "TSEnumMember": + return parent.id !== node; + + case "TSPropertySignature": + if (parent.key === node) { + return !!parent.computed; + } + + return true; + } + + return true; + } + }); + + unwrapExports(isReferenced_1); + + var isScope_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = isScope; + + + + function isScope(node, parent) { + if ((0, generated.isBlockStatement)(node) && ((0, generated.isFunction)(parent) || (0, generated.isCatchClause)(parent))) { + return false; + } + + if ((0, generated.isPattern)(node) && ((0, generated.isFunction)(parent) || (0, generated.isCatchClause)(parent))) { + return true; + } + + return (0, generated.isScopable)(node); + } + }); + + unwrapExports(isScope_1); + + var isSpecifierDefault_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = isSpecifierDefault; + + + + function isSpecifierDefault(specifier) { + return (0, generated.isImportDefaultSpecifier)(specifier) || (0, generated.isIdentifier)(specifier.imported || specifier.exported, { + name: "default" + }); + } + }); + + unwrapExports(isSpecifierDefault_1); + + var isValidES3Identifier_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = isValidES3Identifier; + + var _isValidIdentifier = _interopRequireDefault(isValidIdentifier_1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + const RESERVED_WORDS_ES3_ONLY = new Set(["abstract", "boolean", "byte", "char", "double", "enum", "final", "float", "goto", "implements", "int", "interface", "long", "native", "package", "private", "protected", "public", "short", "static", "synchronized", "throws", "transient", "volatile"]); + + function isValidES3Identifier(name) { + return (0, _isValidIdentifier.default)(name) && !RESERVED_WORDS_ES3_ONLY.has(name); + } + }); + + unwrapExports(isValidES3Identifier_1); + + var isVar_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = isVar; + + + + + + function isVar(node) { + return (0, generated.isVariableDeclaration)(node, { + kind: "var" + }) && !node[constants.BLOCK_SCOPED_SYMBOL]; + } + }); + + unwrapExports(isVar_1); + + var lib$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + var _exportNames = { + react: true, + assertNode: true, + createTypeAnnotationBasedOnTypeof: true, + createUnionTypeAnnotation: true, + createFlowUnionType: true, + createTSUnionType: true, + cloneNode: true, + clone: true, + cloneDeep: true, + cloneDeepWithoutLoc: true, + cloneWithoutLoc: true, + addComment: true, + addComments: true, + inheritInnerComments: true, + inheritLeadingComments: true, + inheritsComments: true, + inheritTrailingComments: true, + removeComments: true, + ensureBlock: true, + toBindingIdentifierName: true, + toBlock: true, + toComputedKey: true, + toExpression: true, + toIdentifier: true, + toKeyAlias: true, + toSequenceExpression: true, + toStatement: true, + valueToNode: true, + appendToMemberExpression: true, + inherits: true, + prependToMemberExpression: true, + removeProperties: true, + removePropertiesDeep: true, + removeTypeDuplicates: true, + getBindingIdentifiers: true, + getOuterBindingIdentifiers: true, + traverse: true, + traverseFast: true, + shallowEqual: true, + is: true, + isBinding: true, + isBlockScoped: true, + isImmutable: true, + isLet: true, + isNode: true, + isNodesEquivalent: true, + isPlaceholderType: true, + isReferenced: true, + isScope: true, + isSpecifierDefault: true, + isType: true, + isValidES3Identifier: true, + isValidIdentifier: true, + isVar: true, + matchesPattern: true, + validate: true, + buildMatchMemberExpression: true + }; + Object.defineProperty(exports, "assertNode", { + enumerable: true, + get: function () { + return _assertNode.default; + } + }); + Object.defineProperty(exports, "createTypeAnnotationBasedOnTypeof", { + enumerable: true, + get: function () { + return _createTypeAnnotationBasedOnTypeof.default; + } + }); + Object.defineProperty(exports, "createUnionTypeAnnotation", { + enumerable: true, + get: function () { + return _createFlowUnionType.default; + } + }); + Object.defineProperty(exports, "createFlowUnionType", { + enumerable: true, + get: function () { + return _createFlowUnionType.default; + } + }); + Object.defineProperty(exports, "createTSUnionType", { + enumerable: true, + get: function () { + return _createTSUnionType.default; + } + }); + Object.defineProperty(exports, "cloneNode", { + enumerable: true, + get: function () { + return _cloneNode.default; + } + }); + Object.defineProperty(exports, "clone", { + enumerable: true, + get: function () { + return _clone.default; + } + }); + Object.defineProperty(exports, "cloneDeep", { + enumerable: true, + get: function () { + return _cloneDeep.default; + } + }); + Object.defineProperty(exports, "cloneDeepWithoutLoc", { + enumerable: true, + get: function () { + return _cloneDeepWithoutLoc.default; + } + }); + Object.defineProperty(exports, "cloneWithoutLoc", { + enumerable: true, + get: function () { + return _cloneWithoutLoc.default; + } + }); + Object.defineProperty(exports, "addComment", { + enumerable: true, + get: function () { + return _addComment.default; + } + }); + Object.defineProperty(exports, "addComments", { + enumerable: true, + get: function () { + return _addComments.default; + } + }); + Object.defineProperty(exports, "inheritInnerComments", { + enumerable: true, + get: function () { + return _inheritInnerComments.default; + } + }); + Object.defineProperty(exports, "inheritLeadingComments", { + enumerable: true, + get: function () { + return _inheritLeadingComments.default; + } + }); + Object.defineProperty(exports, "inheritsComments", { + enumerable: true, + get: function () { + return _inheritsComments.default; + } + }); + Object.defineProperty(exports, "inheritTrailingComments", { + enumerable: true, + get: function () { + return _inheritTrailingComments.default; + } + }); + Object.defineProperty(exports, "removeComments", { + enumerable: true, + get: function () { + return _removeComments.default; + } + }); + Object.defineProperty(exports, "ensureBlock", { + enumerable: true, + get: function () { + return _ensureBlock.default; + } + }); + Object.defineProperty(exports, "toBindingIdentifierName", { + enumerable: true, + get: function () { + return _toBindingIdentifierName.default; + } + }); + Object.defineProperty(exports, "toBlock", { + enumerable: true, + get: function () { + return _toBlock.default; + } + }); + Object.defineProperty(exports, "toComputedKey", { + enumerable: true, + get: function () { + return _toComputedKey.default; + } + }); + Object.defineProperty(exports, "toExpression", { + enumerable: true, + get: function () { + return _toExpression.default; + } + }); + Object.defineProperty(exports, "toIdentifier", { + enumerable: true, + get: function () { + return _toIdentifier.default; + } + }); + Object.defineProperty(exports, "toKeyAlias", { + enumerable: true, + get: function () { + return _toKeyAlias.default; + } + }); + Object.defineProperty(exports, "toSequenceExpression", { + enumerable: true, + get: function () { + return _toSequenceExpression.default; + } + }); + Object.defineProperty(exports, "toStatement", { + enumerable: true, + get: function () { + return _toStatement.default; + } + }); + Object.defineProperty(exports, "valueToNode", { + enumerable: true, + get: function () { + return _valueToNode.default; + } + }); + Object.defineProperty(exports, "appendToMemberExpression", { + enumerable: true, + get: function () { + return _appendToMemberExpression.default; + } + }); + Object.defineProperty(exports, "inherits", { + enumerable: true, + get: function () { + return _inherits.default; + } + }); + Object.defineProperty(exports, "prependToMemberExpression", { + enumerable: true, + get: function () { + return _prependToMemberExpression.default; + } + }); + Object.defineProperty(exports, "removeProperties", { + enumerable: true, + get: function () { + return _removeProperties.default; + } + }); + Object.defineProperty(exports, "removePropertiesDeep", { + enumerable: true, + get: function () { + return _removePropertiesDeep.default; + } + }); + Object.defineProperty(exports, "removeTypeDuplicates", { + enumerable: true, + get: function () { + return _removeTypeDuplicates.default; + } + }); + Object.defineProperty(exports, "getBindingIdentifiers", { + enumerable: true, + get: function () { + return _getBindingIdentifiers.default; + } + }); + Object.defineProperty(exports, "getOuterBindingIdentifiers", { + enumerable: true, + get: function () { + return _getOuterBindingIdentifiers.default; + } + }); + Object.defineProperty(exports, "traverse", { + enumerable: true, + get: function () { + return _traverse.default; + } + }); + Object.defineProperty(exports, "traverseFast", { + enumerable: true, + get: function () { + return _traverseFast.default; + } + }); + Object.defineProperty(exports, "shallowEqual", { + enumerable: true, + get: function () { + return _shallowEqual.default; + } + }); + Object.defineProperty(exports, "is", { + enumerable: true, + get: function () { + return _is.default; + } + }); + Object.defineProperty(exports, "isBinding", { + enumerable: true, + get: function () { + return _isBinding.default; + } + }); + Object.defineProperty(exports, "isBlockScoped", { + enumerable: true, + get: function () { + return _isBlockScoped.default; + } + }); + Object.defineProperty(exports, "isImmutable", { + enumerable: true, + get: function () { + return _isImmutable.default; + } + }); + Object.defineProperty(exports, "isLet", { + enumerable: true, + get: function () { + return _isLet.default; + } + }); + Object.defineProperty(exports, "isNode", { + enumerable: true, + get: function () { + return _isNode.default; + } + }); + Object.defineProperty(exports, "isNodesEquivalent", { + enumerable: true, + get: function () { + return _isNodesEquivalent.default; + } + }); + Object.defineProperty(exports, "isPlaceholderType", { + enumerable: true, + get: function () { + return _isPlaceholderType.default; + } + }); + Object.defineProperty(exports, "isReferenced", { + enumerable: true, + get: function () { + return _isReferenced.default; + } + }); + Object.defineProperty(exports, "isScope", { + enumerable: true, + get: function () { + return _isScope.default; + } + }); + Object.defineProperty(exports, "isSpecifierDefault", { + enumerable: true, + get: function () { + return _isSpecifierDefault.default; + } + }); + Object.defineProperty(exports, "isType", { + enumerable: true, + get: function () { + return _isType.default; + } + }); + Object.defineProperty(exports, "isValidES3Identifier", { + enumerable: true, + get: function () { + return _isValidES3Identifier.default; + } + }); + Object.defineProperty(exports, "isValidIdentifier", { + enumerable: true, + get: function () { + return _isValidIdentifier.default; + } + }); + Object.defineProperty(exports, "isVar", { + enumerable: true, + get: function () { + return _isVar.default; + } + }); + Object.defineProperty(exports, "matchesPattern", { + enumerable: true, + get: function () { + return _matchesPattern.default; + } + }); + Object.defineProperty(exports, "validate", { + enumerable: true, + get: function () { + return _validate.default; + } + }); + Object.defineProperty(exports, "buildMatchMemberExpression", { + enumerable: true, + get: function () { + return _buildMatchMemberExpression.default; + } + }); + exports.react = void 0; + + var _isReactComponent = _interopRequireDefault(isReactComponent_1); + + var _isCompatTag = _interopRequireDefault(isCompatTag_1); + + var _buildChildren = _interopRequireDefault(buildChildren_1); + + var _assertNode = _interopRequireDefault(assertNode_1); + + + + Object.keys(generated$2).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === generated$2[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return generated$2[key]; + } + }); + }); + + var _createTypeAnnotationBasedOnTypeof = _interopRequireDefault(createTypeAnnotationBasedOnTypeof_1); + + var _createFlowUnionType = _interopRequireDefault(createFlowUnionType_1); + + var _createTSUnionType = _interopRequireDefault(createTSUnionType_1); + + + + Object.keys(generated$1).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === generated$1[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return generated$1[key]; + } + }); + }); + + var _cloneNode = _interopRequireDefault(cloneNode_1); + + var _clone = _interopRequireDefault(clone_1$1); + + var _cloneDeep = _interopRequireDefault(cloneDeep_1); + + var _cloneDeepWithoutLoc = _interopRequireDefault(cloneDeepWithoutLoc_1); + + var _cloneWithoutLoc = _interopRequireDefault(cloneWithoutLoc_1); + + var _addComment = _interopRequireDefault(addComment_1); + + var _addComments = _interopRequireDefault(addComments_1); + + var _inheritInnerComments = _interopRequireDefault(inheritInnerComments_1); + + var _inheritLeadingComments = _interopRequireDefault(inheritLeadingComments_1); + + var _inheritsComments = _interopRequireDefault(inheritsComments_1); + + var _inheritTrailingComments = _interopRequireDefault(inheritTrailingComments_1); + + var _removeComments = _interopRequireDefault(removeComments_1); + + + + Object.keys(generated$3).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === generated$3[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return generated$3[key]; + } + }); + }); + + + + Object.keys(constants).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === constants[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return constants[key]; + } + }); + }); + + var _ensureBlock = _interopRequireDefault(ensureBlock_1); + + var _toBindingIdentifierName = _interopRequireDefault(toBindingIdentifierName_1); + + var _toBlock = _interopRequireDefault(toBlock_1); + + var _toComputedKey = _interopRequireDefault(toComputedKey_1); + + var _toExpression = _interopRequireDefault(toExpression_1); + + var _toIdentifier = _interopRequireDefault(toIdentifier_1); + + var _toKeyAlias = _interopRequireDefault(toKeyAlias_1); + + var _toSequenceExpression = _interopRequireDefault(toSequenceExpression_1); + + var _toStatement = _interopRequireDefault(toStatement_1); + + var _valueToNode = _interopRequireDefault(valueToNode_1); + + + + Object.keys(definitions).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === definitions[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return definitions[key]; + } + }); + }); + + var _appendToMemberExpression = _interopRequireDefault(appendToMemberExpression_1); + + var _inherits = _interopRequireDefault(inherits_1); + + var _prependToMemberExpression = _interopRequireDefault(prependToMemberExpression_1); + + var _removeProperties = _interopRequireDefault(removeProperties_1); + + var _removePropertiesDeep = _interopRequireDefault(removePropertiesDeep_1); + + var _removeTypeDuplicates = _interopRequireDefault(removeTypeDuplicates_1); + + var _getBindingIdentifiers = _interopRequireDefault(getBindingIdentifiers_1); + + var _getOuterBindingIdentifiers = _interopRequireDefault(getOuterBindingIdentifiers_1); + + var _traverse = _interopRequireDefault(traverse_1); + + var _traverseFast = _interopRequireDefault(traverseFast_1); + + var _shallowEqual = _interopRequireDefault(shallowEqual_1); + + var _is = _interopRequireDefault(is_1); + + var _isBinding = _interopRequireDefault(isBinding_1); + + var _isBlockScoped = _interopRequireDefault(isBlockScoped_1); + + var _isImmutable = _interopRequireDefault(isImmutable_1); + + var _isLet = _interopRequireDefault(isLet_1); + + var _isNode = _interopRequireDefault(isNode_1); + + var _isNodesEquivalent = _interopRequireDefault(isNodesEquivalent_1); + + var _isPlaceholderType = _interopRequireDefault(isPlaceholderType_1); + + var _isReferenced = _interopRequireDefault(isReferenced_1); + + var _isScope = _interopRequireDefault(isScope_1); + + var _isSpecifierDefault = _interopRequireDefault(isSpecifierDefault_1); + + var _isType = _interopRequireDefault(isType_1); + + var _isValidES3Identifier = _interopRequireDefault(isValidES3Identifier_1); + + var _isValidIdentifier = _interopRequireDefault(isValidIdentifier_1); + + var _isVar = _interopRequireDefault(isVar_1); + + var _matchesPattern = _interopRequireDefault(matchesPattern_1); + + var _validate = _interopRequireDefault(validate_1); + + var _buildMatchMemberExpression = _interopRequireDefault(buildMatchMemberExpression_1); + + + + Object.keys(generated).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === generated[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return generated[key]; + } + }); + }); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + const react = { + isReactComponent: _isReactComponent.default, + isCompatTag: _isCompatTag.default, + buildChildren: _buildChildren.default + }; + exports.react = react; + }); + + unwrapExports(lib$1); + var lib_1 = lib$1.react; + + var virtualTypes = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.ForAwaitStatement = exports.NumericLiteralTypeAnnotation = exports.ExistentialTypeParam = exports.SpreadProperty = exports.RestProperty = exports.Flow = exports.Pure = exports.Generated = exports.User = exports.Var = exports.BlockScoped = exports.Referenced = exports.Scope = exports.Expression = exports.Statement = exports.BindingIdentifier = exports.ReferencedMemberExpression = exports.ReferencedIdentifier = void 0; + + var t = _interopRequireWildcard(lib$1); + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + const ReferencedIdentifier = { + types: ["Identifier", "JSXIdentifier"], + + checkPath(path, opts) { + const { + node, + parent + } = path; + + if (!t.isIdentifier(node, opts) && !t.isJSXMemberExpression(parent, opts)) { + if (t.isJSXIdentifier(node, opts)) { + if (t.react.isCompatTag(node.name)) return false; + } else { + return false; + } + } + + return t.isReferenced(node, parent, path.parentPath.parent); + } + + }; + exports.ReferencedIdentifier = ReferencedIdentifier; + const ReferencedMemberExpression = { + types: ["MemberExpression"], + + checkPath({ + node, + parent + }) { + return t.isMemberExpression(node) && t.isReferenced(node, parent); + } + + }; + exports.ReferencedMemberExpression = ReferencedMemberExpression; + const BindingIdentifier = { + types: ["Identifier"], + + checkPath(path) { + const { + node, + parent + } = path; + const grandparent = path.parentPath.parent; + return t.isIdentifier(node) && t.isBinding(node, parent, grandparent); + } + + }; + exports.BindingIdentifier = BindingIdentifier; + const Statement = { + types: ["Statement"], + + checkPath({ + node, + parent + }) { + if (t.isStatement(node)) { + if (t.isVariableDeclaration(node)) { + if (t.isForXStatement(parent, { + left: node + })) return false; + if (t.isForStatement(parent, { + init: node + })) return false; + } + + return true; + } else { + return false; + } + } + + }; + exports.Statement = Statement; + const Expression = { + types: ["Expression"], + + checkPath(path) { + if (path.isIdentifier()) { + return path.isReferencedIdentifier(); + } else { + return t.isExpression(path.node); + } + } + + }; + exports.Expression = Expression; + const Scope = { + types: ["Scopable", "Pattern"], + + checkPath(path) { + return t.isScope(path.node, path.parent); + } + + }; + exports.Scope = Scope; + const Referenced = { + checkPath(path) { + return t.isReferenced(path.node, path.parent); + } + + }; + exports.Referenced = Referenced; + const BlockScoped = { + checkPath(path) { + return t.isBlockScoped(path.node); + } + + }; + exports.BlockScoped = BlockScoped; + const Var = { + types: ["VariableDeclaration"], + + checkPath(path) { + return t.isVar(path.node); + } + + }; + exports.Var = Var; + const User = { + checkPath(path) { + return path.node && !!path.node.loc; + } + + }; + exports.User = User; + const Generated = { + checkPath(path) { + return !path.isUser(); + } + + }; + exports.Generated = Generated; + const Pure = { + checkPath(path, opts) { + return path.scope.isPure(path.node, opts); + } + + }; + exports.Pure = Pure; + const Flow = { + types: ["Flow", "ImportDeclaration", "ExportDeclaration", "ImportSpecifier"], + + checkPath({ + node + }) { + if (t.isFlow(node)) { + return true; + } else if (t.isImportDeclaration(node)) { + return node.importKind === "type" || node.importKind === "typeof"; + } else if (t.isExportDeclaration(node)) { + return node.exportKind === "type"; + } else if (t.isImportSpecifier(node)) { + return node.importKind === "type" || node.importKind === "typeof"; + } else { + return false; + } + } + + }; + exports.Flow = Flow; + const RestProperty = { + types: ["RestElement"], + + checkPath(path) { + return path.parentPath && path.parentPath.isObjectPattern(); + } + + }; + exports.RestProperty = RestProperty; + const SpreadProperty = { + types: ["RestElement"], + + checkPath(path) { + return path.parentPath && path.parentPath.isObjectExpression(); + } + + }; + exports.SpreadProperty = SpreadProperty; + const ExistentialTypeParam = { + types: ["ExistsTypeAnnotation"] + }; + exports.ExistentialTypeParam = ExistentialTypeParam; + const NumericLiteralTypeAnnotation = { + types: ["NumberLiteralTypeAnnotation"] + }; + exports.NumericLiteralTypeAnnotation = NumericLiteralTypeAnnotation; + const ForAwaitStatement = { + types: ["ForOfStatement"], + + checkPath({ + node + }) { + return node.await === true; + } + + }; + exports.ForAwaitStatement = ForAwaitStatement; + }); + + unwrapExports(virtualTypes); + var virtualTypes_1 = virtualTypes.ForAwaitStatement; + var virtualTypes_2 = virtualTypes.NumericLiteralTypeAnnotation; + var virtualTypes_3 = virtualTypes.ExistentialTypeParam; + var virtualTypes_4 = virtualTypes.SpreadProperty; + var virtualTypes_5 = virtualTypes.RestProperty; + var virtualTypes_6 = virtualTypes.Flow; + var virtualTypes_7 = virtualTypes.Pure; + var virtualTypes_8 = virtualTypes.Generated; + var virtualTypes_9 = virtualTypes.User; + var virtualTypes_10 = virtualTypes.Var; + var virtualTypes_11 = virtualTypes.BlockScoped; + var virtualTypes_12 = virtualTypes.Referenced; + var virtualTypes_13 = virtualTypes.Scope; + var virtualTypes_14 = virtualTypes.Expression; + var virtualTypes_15 = virtualTypes.Statement; + var virtualTypes_16 = virtualTypes.BindingIdentifier; + var virtualTypes_17 = virtualTypes.ReferencedMemberExpression; + var virtualTypes_18 = virtualTypes.ReferencedIdentifier; + + var browser$1 = true; + + /** + * Helpers. + */ + + var s = 1000; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + + /** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + + var ms = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); + }; + + /** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + + function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } + } + + /** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; + } + + /** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; + } + + /** + * Pluralization helper. + */ + + function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); + } + + /** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = ms; + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; + } + + var common = setup; + + var browser$2 = createCommonjsModule(function (module, exports) { + /* eslint-env browser */ + + /** + * This is the web browser implementation of `debug()`. + */ + + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.storage = localstorage(); + exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; + })(); + + /** + * Colors. + */ + + exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' + ]; + + /** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + + // eslint-disable-next-line complexity + function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); + } + + /** + * Colorize log arguments if enabled. + * + * @api public + */ + + function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); + } + + /** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ + exports.log = console.debug || console.log || (() => {}); + + /** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + } + + /** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; + } + + /** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + + function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + } + + module.exports = common(exports); + + const {formatters} = module.exports; + + /** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + + formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } + }; + }); + var browser_1 = browser$2.formatArgs; + var browser_2 = browser$2.save; + var browser_3 = browser$2.load; + var browser_4 = browser$2.useColors; + var browser_5 = browser$2.storage; + var browser_6 = browser$2.destroy; + var browser_7 = browser$2.colors; + var browser_8 = browser$2.log; + + // MIT lisence + // from https://github.com/substack/tty-browserify/blob/1ba769a6429d242f36226538835b4034bf6b7886/index.js + + function isatty() { + return false; + } + + function ReadStream() { + throw new Error('tty.ReadStream is not implemented'); + } + + function WriteStream() { + throw new Error('tty.ReadStream is not implemented'); + } + + var tty = { + isatty: isatty, + ReadStream: ReadStream, + WriteStream: WriteStream + }; + + var tty$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + isatty: isatty, + ReadStream: ReadStream, + WriteStream: WriteStream, + 'default': tty + }); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + + var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + var _kMaxLength = kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + + function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0; + } + return Buffer.alloc(+length) + } + Buffer.isBuffer = isBuffer; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + var bufferEs6 = /*#__PURE__*/Object.freeze({ + __proto__: null, + INSPECT_MAX_BYTES: INSPECT_MAX_BYTES, + kMaxLength: _kMaxLength, + Buffer: Buffer, + SlowBuffer: SlowBuffer, + isBuffer: isBuffer + }); + + var inherits; + if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$1 = inherits; + + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject$1(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + } + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + } + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction$1(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction$1(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp$1(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray$2(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction$1(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp$1(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp$1(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty$b(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty$b(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray$2(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNullOrUndefined(arg) { + return arg == null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString(arg) { + return typeof arg === 'string'; + } + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp$1(re) { + return isObject$1(re) && objectToString$1(re) === '[object RegExp]'; + } + + function isObject$1(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject$1(d) && objectToString$1(d) === '[object Date]'; + } + + function isError(e) { + return isObject$1(e) && + (objectToString$1(e) === '[object Error]' || e instanceof Error); + } + + function isFunction$1(arg) { + return typeof arg === 'function'; + } + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + + function isBuffer$1(maybeBuf) { + return isBuffer(maybeBuf); + } + + function objectToString$1(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + function log() { + console.log('%s - %s', timestamp(), format.apply(null, arguments)); + } + + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject$1(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + } + function hasOwnProperty$b(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var util = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer$1, + isPrimitive: isPrimitive, + isFunction: isFunction$1, + isError: isError, + isDate: isDate, + isObject: isObject$1, + isRegExp: isRegExp$1, + isUndefined: isUndefined, + isSymbol: isSymbol, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray$2, + inspect: inspect, + deprecate: deprecate, + format: format, + debuglog: debuglog + }; + + var util$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + format: format, + deprecate: deprecate, + debuglog: debuglog, + inspect: inspect, + isArray: isArray$2, + isBoolean: isBoolean, + isNull: isNull, + isNullOrUndefined: isNullOrUndefined, + isNumber: isNumber, + isString: isString, + isSymbol: isSymbol, + isUndefined: isUndefined, + isRegExp: isRegExp$1, + isObject: isObject$1, + isDate: isDate, + isError: isError, + isFunction: isFunction$1, + isPrimitive: isPrimitive, + isBuffer: isBuffer$1, + log: log, + inherits: inherits$1, + _extend: _extend, + 'default': util + }); + + /* + The MIT License (MIT) + + Copyright (c) 2016 CoderPuppy + + 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. + + */ + var _endianness; + function endianness() { + if (typeof _endianness === 'undefined') { + var a = new ArrayBuffer(2); + var b = new Uint8Array(a); + var c = new Uint16Array(a); + b[0] = 1; + b[1] = 2; + if (c[0] === 258) { + _endianness = 'BE'; + } else if (c[0] === 513){ + _endianness = 'LE'; + } else { + throw new Error('unable to figure out endianess'); + } + } + return _endianness; + } + + function hostname() { + if (typeof global$1.location !== 'undefined') { + return global$1.location.hostname + } else return ''; + } + + function loadavg() { + return []; + } + + function uptime$1() { + return 0; + } + + function freemem() { + return Number.MAX_VALUE; + } + + function totalmem() { + return Number.MAX_VALUE; + } + + function cpus() { + return []; + } + + function type() { + return 'Browser'; + } + + function release$1 () { + if (typeof global$1.navigator !== 'undefined') { + return global$1.navigator.appVersion; + } + return ''; + } + + function networkInterfaces(){} + function getNetworkInterfaces(){} + + function arch() { + return 'javascript'; + } + + function platform$1() { + return 'browser'; + } + + function tmpDir() { + return '/tmp'; + } + var tmpdir = tmpDir; + + var EOL = '\n'; + var os = { + EOL: EOL, + tmpdir: tmpdir, + tmpDir: tmpDir, + networkInterfaces:networkInterfaces, + getNetworkInterfaces: getNetworkInterfaces, + release: release$1, + type: type, + cpus: cpus, + totalmem: totalmem, + freemem: freemem, + uptime: uptime$1, + loadavg: loadavg, + hostname: hostname, + endianness: endianness, + }; + + var os$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + endianness: endianness, + hostname: hostname, + loadavg: loadavg, + uptime: uptime$1, + freemem: freemem, + totalmem: totalmem, + cpus: cpus, + type: type, + release: release$1, + networkInterfaces: networkInterfaces, + getNetworkInterfaces: getNetworkInterfaces, + arch: arch, + platform: platform$1, + tmpDir: tmpDir, + tmpdir: tmpdir, + EOL: EOL, + 'default': os + }); + + var hasFlag = (flag, argv) => { + argv = argv || process.argv; + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const pos = argv.indexOf(prefix + flag); + const terminatorPos = argv.indexOf('--'); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); + }; + + var os$2 = getCjsExportFromNamespace(os$1); + + const env$1 = process.env; + + let forceColor; + if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false')) { + forceColor = false; + } else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = true; + } + if ('FORCE_COLOR' in env$1) { + forceColor = env$1.FORCE_COLOR.length === 0 || parseInt(env$1.FORCE_COLOR, 10) !== 0; + } + + function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; + } + + function supportsColor(stream) { + if (forceColor === false) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } + + const min = forceColor ? 1 : 0; + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + const osRelease = os$2.release().split('.'); + if ( + Number(process.versions.node.split('.')[0]) >= 8 && + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env$1) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env$1) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env$1.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env$1) { + const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env$1.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env$1.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) { + return 1; + } + + if ('COLORTERM' in env$1) { + return 1; + } + + if (env$1.TERM === 'dumb') { + return min; + } + + return min; + } + + function getSupportLevel(stream) { + const level = supportsColor(stream); + return translateLevel(level); + } + + var supportsColor_1 = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) + }; + + var tty$2 = getCjsExportFromNamespace(tty$1); + + var util$2 = getCjsExportFromNamespace(util$1); + + var node = createCommonjsModule(function (module, exports) { + /** + * Module dependencies. + */ + + + + + /** + * This is the Node.js implementation of `debug()`. + */ + + exports.init = init; + exports.log = log; + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.destroy = util$2.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' + ); + + /** + * Colors. + */ + + exports.colors = [6, 2, 3, 4, 5, 1]; + + try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = supportsColor_1; + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } + } catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. + } + + /** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + + exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); + }).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; + }, {}); + + /** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + + function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty$2.isatty(process.stderr.fd); + } + + /** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + + function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } + } + + function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; + } + + /** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + + function log(...args) { + return process.stderr.write(util$2.format(...args) + '\n'); + } + + /** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } + } + + /** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + + function load() { + return process.env.DEBUG; + } + + /** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + + function init(debug) { + debug.inspectOpts = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } + } + + module.exports = common(exports); + + const {formatters} = module.exports; + + /** + * Map %o to `util.inspect()`, all on a single line. + */ + + formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util$2.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); + }; + + /** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + + formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util$2.inspect(v, this.inspectOpts); + }; + }); + var node_1 = node.init; + var node_2 = node.log; + var node_3 = node.formatArgs; + var node_4 = node.save; + var node_5 = node.load; + var node_6 = node.useColors; + var node_7 = node.destroy; + var node_8 = node.colors; + var node_9 = node.inspectOpts; + + var src = createCommonjsModule(function (module) { + /** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ + + if (typeof process === 'undefined' || process.type === 'renderer' || browser$1 === true || process.__nwjs) { + module.exports = browser$2; + } else { + module.exports = node; + } + }); + + var binding$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = void 0; + + class Binding { + constructor({ + identifier, + scope, + path, + kind + }) { + this.constantViolations = []; + this.constant = true; + this.referencePaths = []; + this.referenced = false; + this.references = 0; + this.identifier = identifier; + this.scope = scope; + this.path = path; + this.kind = kind; + this.clearValue(); + } + + deoptValue() { + this.clearValue(); + this.hasDeoptedValue = true; + } + + setValue(value) { + if (this.hasDeoptedValue) return; + this.hasValue = true; + this.value = value; + } + + clearValue() { + this.hasDeoptedValue = false; + this.hasValue = false; + this.value = null; + } + + reassign(path) { + this.constant = false; + + if (this.constantViolations.indexOf(path) !== -1) { + return; + } + + this.constantViolations.push(path); + } + + reference(path) { + if (this.referencePaths.indexOf(path) !== -1) { + return; + } + + this.referenced = true; + this.references++; + this.referencePaths.push(path); + } + + dereference() { + this.references--; + this.referenced = !!this.references; + } + + } + + exports.default = Binding; + }); + + unwrapExports(binding$1); + + var lib$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = splitExportDeclaration; + + var t = _interopRequireWildcard(lib$1); + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + function splitExportDeclaration(exportDeclaration) { + if (!exportDeclaration.isExportDeclaration()) { + throw new Error("Only export declarations can be split."); + } + + const isDefault = exportDeclaration.isExportDefaultDeclaration(); + const declaration = exportDeclaration.get("declaration"); + const isClassDeclaration = declaration.isClassDeclaration(); + + if (isDefault) { + const standaloneDeclaration = declaration.isFunctionDeclaration() || isClassDeclaration; + const scope = declaration.isScope() ? declaration.scope.parent : declaration.scope; + let id = declaration.node.id; + let needBindingRegistration = false; + + if (!id) { + needBindingRegistration = true; + id = scope.generateUidIdentifier("default"); + + if (standaloneDeclaration || declaration.isFunctionExpression() || declaration.isClassExpression()) { + declaration.node.id = t.cloneNode(id); + } + } + + const updatedDeclaration = standaloneDeclaration ? declaration : t.variableDeclaration("var", [t.variableDeclarator(t.cloneNode(id), declaration.node)]); + const updatedExportDeclaration = t.exportNamedDeclaration(null, [t.exportSpecifier(t.cloneNode(id), t.identifier("default"))]); + exportDeclaration.insertAfter(updatedExportDeclaration); + exportDeclaration.replaceWith(updatedDeclaration); + + if (needBindingRegistration) { + scope.registerDeclaration(exportDeclaration); + } + + return exportDeclaration; + } + + if (exportDeclaration.get("specifiers").length > 0) { + throw new Error("It doesn't make sense to split exported specifiers."); + } + + const bindingIdentifiers = declaration.getOuterBindingIdentifiers(); + const specifiers = Object.keys(bindingIdentifiers).map(name => { + return t.exportSpecifier(t.identifier(name), t.identifier(name)); + }); + const aliasDeclar = t.exportNamedDeclaration(null, specifiers); + exportDeclaration.insertAfter(aliasDeclar); + exportDeclaration.replaceWith(declaration.node); + return exportDeclaration; + } + }); + + unwrapExports(lib$2); + + var renamer = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = void 0; + + var _binding = _interopRequireDefault(binding$1); + + var _helperSplitExportDeclaration = _interopRequireDefault(lib$2); + + var t = _interopRequireWildcard(lib$1); + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + const renameVisitor = { + ReferencedIdentifier({ + node + }, state) { + if (node.name === state.oldName) { + node.name = state.newName; + } + }, + + Scope(path, state) { + if (!path.scope.bindingIdentifierEquals(state.oldName, state.binding.identifier)) { + path.skip(); + } + }, + + "AssignmentExpression|Declaration|VariableDeclarator"(path, state) { + if (path.isVariableDeclaration()) return; + const ids = path.getOuterBindingIdentifiers(); + + for (const name in ids) { + if (name === state.oldName) ids[name].name = state.newName; + } + } + + }; + + class Renamer { + constructor(binding, oldName, newName) { + this.newName = newName; + this.oldName = oldName; + this.binding = binding; + } + + maybeConvertFromExportDeclaration(parentDeclar) { + const maybeExportDeclar = parentDeclar.parentPath; + + if (!maybeExportDeclar.isExportDeclaration()) { + return; + } + + if (maybeExportDeclar.isExportDefaultDeclaration() && !maybeExportDeclar.get("declaration").node.id) { + return; + } + + (0, _helperSplitExportDeclaration.default)(maybeExportDeclar); + } + + maybeConvertFromClassFunctionDeclaration(path) { + return; + } + + maybeConvertFromClassFunctionExpression(path) { + return; + } + + rename(block) { + const { + binding, + oldName, + newName + } = this; + const { + scope, + path + } = binding; + const parentDeclar = path.find(path => path.isDeclaration() || path.isFunctionExpression() || path.isClassExpression()); + + if (parentDeclar) { + const bindingIds = parentDeclar.getOuterBindingIdentifiers(); + + if (bindingIds[oldName] === binding.identifier) { + this.maybeConvertFromExportDeclaration(parentDeclar); + } + } + + scope.traverse(block || scope.block, renameVisitor, this); + + if (!block) { + scope.removeOwnBinding(oldName); + scope.bindings[newName] = binding; + this.binding.identifier.name = newName; + } + + if (binding.type === "hoisted") ; + + if (parentDeclar) { + this.maybeConvertFromClassFunctionDeclaration(parentDeclar); + this.maybeConvertFromClassFunctionExpression(parentDeclar); + } + } + + } + + exports.default = Renamer; + }); + + unwrapExports(renamer); + + var builtin = { + "Array": false, + "ArrayBuffer": false, + Atomics: false, + BigInt: false, + BigInt64Array: false, + BigUint64Array: false, + "Boolean": false, + constructor: false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + globalThis: false, + hasOwnProperty: false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + isPrototypeOf: false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + propertyIsEnumerable: false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + SharedArrayBuffer: false, + "String": false, + "Symbol": false, + "SyntaxError": false, + toLocaleString: false, + toString: false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + valueOf: false, + "WeakMap": false, + "WeakSet": false + }; + var es5 = { + "Array": false, + "Boolean": false, + constructor: false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Function": false, + hasOwnProperty: false, + "Infinity": false, + "isFinite": false, + "isNaN": false, + isPrototypeOf: false, + "JSON": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + propertyIsEnumerable: false, + "RangeError": false, + "ReferenceError": false, + "RegExp": false, + "String": false, + "SyntaxError": false, + toLocaleString: false, + toString: false, + "TypeError": false, + "undefined": false, + "unescape": false, + "URIError": false, + valueOf: false + }; + var es2015 = { + "Array": false, + "ArrayBuffer": false, + "Boolean": false, + constructor: false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + hasOwnProperty: false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + isPrototypeOf: false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + propertyIsEnumerable: false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + toLocaleString: false, + toString: false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + valueOf: false, + "WeakMap": false, + "WeakSet": false + }; + var es2017 = { + "Array": false, + "ArrayBuffer": false, + Atomics: false, + "Boolean": false, + constructor: false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + hasOwnProperty: false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + isPrototypeOf: false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + propertyIsEnumerable: false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + SharedArrayBuffer: false, + "String": false, + "Symbol": false, + "SyntaxError": false, + toLocaleString: false, + toString: false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + valueOf: false, + "WeakMap": false, + "WeakSet": false + }; + var browser$3 = { + AbortController: false, + AbortSignal: false, + addEventListener: false, + alert: false, + AnalyserNode: false, + Animation: false, + AnimationEffectReadOnly: false, + AnimationEffectTiming: false, + AnimationEffectTimingReadOnly: false, + AnimationEvent: false, + AnimationPlaybackEvent: false, + AnimationTimeline: false, + applicationCache: false, + ApplicationCache: false, + ApplicationCacheErrorEvent: false, + atob: false, + Attr: false, + Audio: false, + AudioBuffer: false, + AudioBufferSourceNode: false, + AudioContext: false, + AudioDestinationNode: false, + AudioListener: false, + AudioNode: false, + AudioParam: false, + AudioProcessingEvent: false, + AudioScheduledSourceNode: false, + "AudioWorkletGlobalScope ": false, + AudioWorkletNode: false, + AudioWorkletProcessor: false, + BarProp: false, + BaseAudioContext: false, + BatteryManager: false, + BeforeUnloadEvent: false, + BiquadFilterNode: false, + Blob: false, + BlobEvent: false, + blur: false, + BroadcastChannel: false, + btoa: false, + BudgetService: false, + ByteLengthQueuingStrategy: false, + Cache: false, + caches: false, + CacheStorage: false, + cancelAnimationFrame: false, + cancelIdleCallback: false, + CanvasCaptureMediaStreamTrack: false, + CanvasGradient: false, + CanvasPattern: false, + CanvasRenderingContext2D: false, + ChannelMergerNode: false, + ChannelSplitterNode: false, + CharacterData: false, + clearInterval: false, + clearTimeout: false, + clientInformation: false, + ClipboardEvent: false, + close: false, + closed: false, + CloseEvent: false, + Comment: false, + CompositionEvent: false, + confirm: false, + console: false, + ConstantSourceNode: false, + ConvolverNode: false, + CountQueuingStrategy: false, + createImageBitmap: false, + Credential: false, + CredentialsContainer: false, + crypto: false, + Crypto: false, + CryptoKey: false, + CSS: false, + CSSConditionRule: false, + CSSFontFaceRule: false, + CSSGroupingRule: false, + CSSImportRule: false, + CSSKeyframeRule: false, + CSSKeyframesRule: false, + CSSMediaRule: false, + CSSNamespaceRule: false, + CSSPageRule: false, + CSSRule: false, + CSSRuleList: false, + CSSStyleDeclaration: false, + CSSStyleRule: false, + CSSStyleSheet: false, + CSSSupportsRule: false, + CustomElementRegistry: false, + customElements: false, + CustomEvent: false, + DataTransfer: false, + DataTransferItem: false, + DataTransferItemList: false, + defaultstatus: false, + defaultStatus: false, + DelayNode: false, + DeviceMotionEvent: false, + DeviceOrientationEvent: false, + devicePixelRatio: false, + dispatchEvent: false, + document: false, + Document: false, + DocumentFragment: false, + DocumentType: false, + DOMError: false, + DOMException: false, + DOMImplementation: false, + DOMMatrix: false, + DOMMatrixReadOnly: false, + DOMParser: false, + DOMPoint: false, + DOMPointReadOnly: false, + DOMQuad: false, + DOMRect: false, + DOMRectReadOnly: false, + DOMStringList: false, + DOMStringMap: false, + DOMTokenList: false, + DragEvent: false, + DynamicsCompressorNode: false, + Element: false, + ErrorEvent: false, + event: false, + Event: false, + EventSource: false, + EventTarget: false, + external: false, + fetch: false, + File: false, + FileList: false, + FileReader: false, + find: false, + focus: false, + FocusEvent: false, + FontFace: false, + FontFaceSetLoadEvent: false, + FormData: false, + frameElement: false, + frames: false, + GainNode: false, + Gamepad: false, + GamepadButton: false, + GamepadEvent: false, + getComputedStyle: false, + getSelection: false, + HashChangeEvent: false, + Headers: false, + history: false, + History: false, + HTMLAllCollection: false, + HTMLAnchorElement: false, + HTMLAreaElement: false, + HTMLAudioElement: false, + HTMLBaseElement: false, + HTMLBodyElement: false, + HTMLBRElement: false, + HTMLButtonElement: false, + HTMLCanvasElement: false, + HTMLCollection: false, + HTMLContentElement: false, + HTMLDataElement: false, + HTMLDataListElement: false, + HTMLDetailsElement: false, + HTMLDialogElement: false, + HTMLDirectoryElement: false, + HTMLDivElement: false, + HTMLDListElement: false, + HTMLDocument: false, + HTMLElement: false, + HTMLEmbedElement: false, + HTMLFieldSetElement: false, + HTMLFontElement: false, + HTMLFormControlsCollection: false, + HTMLFormElement: false, + HTMLFrameElement: false, + HTMLFrameSetElement: false, + HTMLHeadElement: false, + HTMLHeadingElement: false, + HTMLHRElement: false, + HTMLHtmlElement: false, + HTMLIFrameElement: false, + HTMLImageElement: false, + HTMLInputElement: false, + HTMLLabelElement: false, + HTMLLegendElement: false, + HTMLLIElement: false, + HTMLLinkElement: false, + HTMLMapElement: false, + HTMLMarqueeElement: false, + HTMLMediaElement: false, + HTMLMenuElement: false, + HTMLMetaElement: false, + HTMLMeterElement: false, + HTMLModElement: false, + HTMLObjectElement: false, + HTMLOListElement: false, + HTMLOptGroupElement: false, + HTMLOptionElement: false, + HTMLOptionsCollection: false, + HTMLOutputElement: false, + HTMLParagraphElement: false, + HTMLParamElement: false, + HTMLPictureElement: false, + HTMLPreElement: false, + HTMLProgressElement: false, + HTMLQuoteElement: false, + HTMLScriptElement: false, + HTMLSelectElement: false, + HTMLShadowElement: false, + HTMLSlotElement: false, + HTMLSourceElement: false, + HTMLSpanElement: false, + HTMLStyleElement: false, + HTMLTableCaptionElement: false, + HTMLTableCellElement: false, + HTMLTableColElement: false, + HTMLTableElement: false, + HTMLTableRowElement: false, + HTMLTableSectionElement: false, + HTMLTemplateElement: false, + HTMLTextAreaElement: false, + HTMLTimeElement: false, + HTMLTitleElement: false, + HTMLTrackElement: false, + HTMLUListElement: false, + HTMLUnknownElement: false, + HTMLVideoElement: false, + IDBCursor: false, + IDBCursorWithValue: false, + IDBDatabase: false, + IDBFactory: false, + IDBIndex: false, + IDBKeyRange: false, + IDBObjectStore: false, + IDBOpenDBRequest: false, + IDBRequest: false, + IDBTransaction: false, + IDBVersionChangeEvent: false, + IdleDeadline: false, + IIRFilterNode: false, + Image: false, + ImageBitmap: false, + ImageBitmapRenderingContext: false, + ImageCapture: false, + ImageData: false, + indexedDB: false, + innerHeight: false, + innerWidth: false, + InputEvent: false, + IntersectionObserver: false, + IntersectionObserverEntry: false, + "Intl": false, + isSecureContext: false, + KeyboardEvent: false, + KeyframeEffect: false, + KeyframeEffectReadOnly: false, + length: false, + localStorage: false, + location: true, + Location: false, + locationbar: false, + matchMedia: false, + MediaDeviceInfo: false, + MediaDevices: false, + MediaElementAudioSourceNode: false, + MediaEncryptedEvent: false, + MediaError: false, + MediaKeyMessageEvent: false, + MediaKeySession: false, + MediaKeyStatusMap: false, + MediaKeySystemAccess: false, + MediaList: false, + MediaQueryList: false, + MediaQueryListEvent: false, + MediaRecorder: false, + MediaSettingsRange: false, + MediaSource: false, + MediaStream: false, + MediaStreamAudioDestinationNode: false, + MediaStreamAudioSourceNode: false, + MediaStreamEvent: false, + MediaStreamTrack: false, + MediaStreamTrackEvent: false, + menubar: false, + MessageChannel: false, + MessageEvent: false, + MessagePort: false, + MIDIAccess: false, + MIDIConnectionEvent: false, + MIDIInput: false, + MIDIInputMap: false, + MIDIMessageEvent: false, + MIDIOutput: false, + MIDIOutputMap: false, + MIDIPort: false, + MimeType: false, + MimeTypeArray: false, + MouseEvent: false, + moveBy: false, + moveTo: false, + MutationEvent: false, + MutationObserver: false, + MutationRecord: false, + name: false, + NamedNodeMap: false, + NavigationPreloadManager: false, + navigator: false, + Navigator: false, + NetworkInformation: false, + Node: false, + NodeFilter: false, + NodeIterator: false, + NodeList: false, + Notification: false, + OfflineAudioCompletionEvent: false, + OfflineAudioContext: false, + offscreenBuffering: false, + OffscreenCanvas: true, + onabort: true, + onafterprint: true, + onanimationend: true, + onanimationiteration: true, + onanimationstart: true, + onappinstalled: true, + onauxclick: true, + onbeforeinstallprompt: true, + onbeforeprint: true, + onbeforeunload: true, + onblur: true, + oncancel: true, + oncanplay: true, + oncanplaythrough: true, + onchange: true, + onclick: true, + onclose: true, + oncontextmenu: true, + oncuechange: true, + ondblclick: true, + ondevicemotion: true, + ondeviceorientation: true, + ondeviceorientationabsolute: true, + ondrag: true, + ondragend: true, + ondragenter: true, + ondragleave: true, + ondragover: true, + ondragstart: true, + ondrop: true, + ondurationchange: true, + onemptied: true, + onended: true, + onerror: true, + onfocus: true, + ongotpointercapture: true, + onhashchange: true, + oninput: true, + oninvalid: true, + onkeydown: true, + onkeypress: true, + onkeyup: true, + onlanguagechange: true, + onload: true, + onloadeddata: true, + onloadedmetadata: true, + onloadstart: true, + onlostpointercapture: true, + onmessage: true, + onmessageerror: true, + onmousedown: true, + onmouseenter: true, + onmouseleave: true, + onmousemove: true, + onmouseout: true, + onmouseover: true, + onmouseup: true, + onmousewheel: true, + onoffline: true, + ononline: true, + onpagehide: true, + onpageshow: true, + onpause: true, + onplay: true, + onplaying: true, + onpointercancel: true, + onpointerdown: true, + onpointerenter: true, + onpointerleave: true, + onpointermove: true, + onpointerout: true, + onpointerover: true, + onpointerup: true, + onpopstate: true, + onprogress: true, + onratechange: true, + onrejectionhandled: true, + onreset: true, + onresize: true, + onscroll: true, + onsearch: true, + onseeked: true, + onseeking: true, + onselect: true, + onstalled: true, + onstorage: true, + onsubmit: true, + onsuspend: true, + ontimeupdate: true, + ontoggle: true, + ontransitionend: true, + onunhandledrejection: true, + onunload: true, + onvolumechange: true, + onwaiting: true, + onwheel: true, + open: false, + openDatabase: false, + opener: false, + Option: false, + origin: false, + OscillatorNode: false, + outerHeight: false, + outerWidth: false, + PageTransitionEvent: false, + pageXOffset: false, + pageYOffset: false, + PannerNode: false, + parent: false, + Path2D: false, + PaymentAddress: false, + PaymentRequest: false, + PaymentRequestUpdateEvent: false, + PaymentResponse: false, + performance: false, + Performance: false, + PerformanceEntry: false, + PerformanceLongTaskTiming: false, + PerformanceMark: false, + PerformanceMeasure: false, + PerformanceNavigation: false, + PerformanceNavigationTiming: false, + PerformanceObserver: false, + PerformanceObserverEntryList: false, + PerformancePaintTiming: false, + PerformanceResourceTiming: false, + PerformanceTiming: false, + PeriodicWave: false, + Permissions: false, + PermissionStatus: false, + personalbar: false, + PhotoCapabilities: false, + Plugin: false, + PluginArray: false, + PointerEvent: false, + PopStateEvent: false, + postMessage: false, + Presentation: false, + PresentationAvailability: false, + PresentationConnection: false, + PresentationConnectionAvailableEvent: false, + PresentationConnectionCloseEvent: false, + PresentationConnectionList: false, + PresentationReceiver: false, + PresentationRequest: false, + print: false, + ProcessingInstruction: false, + ProgressEvent: false, + PromiseRejectionEvent: false, + prompt: false, + PushManager: false, + PushSubscription: false, + PushSubscriptionOptions: false, + queueMicrotask: false, + RadioNodeList: false, + Range: false, + ReadableStream: false, + registerProcessor: false, + RemotePlayback: false, + removeEventListener: false, + Request: false, + requestAnimationFrame: false, + requestIdleCallback: false, + resizeBy: false, + ResizeObserver: false, + ResizeObserverEntry: false, + resizeTo: false, + Response: false, + RTCCertificate: false, + RTCDataChannel: false, + RTCDataChannelEvent: false, + RTCDtlsTransport: false, + RTCIceCandidate: false, + RTCIceGatherer: false, + RTCIceTransport: false, + RTCPeerConnection: false, + RTCPeerConnectionIceEvent: false, + RTCRtpContributingSource: false, + RTCRtpReceiver: false, + RTCRtpSender: false, + RTCSctpTransport: false, + RTCSessionDescription: false, + RTCStatsReport: false, + RTCTrackEvent: false, + screen: false, + Screen: false, + screenLeft: false, + ScreenOrientation: false, + screenTop: false, + screenX: false, + screenY: false, + ScriptProcessorNode: false, + scroll: false, + scrollbars: false, + scrollBy: false, + scrollTo: false, + scrollX: false, + scrollY: false, + SecurityPolicyViolationEvent: false, + Selection: false, + self: false, + ServiceWorker: false, + ServiceWorkerContainer: false, + ServiceWorkerRegistration: false, + sessionStorage: false, + setInterval: false, + setTimeout: false, + ShadowRoot: false, + SharedWorker: false, + SourceBuffer: false, + SourceBufferList: false, + speechSynthesis: false, + SpeechSynthesisEvent: false, + SpeechSynthesisUtterance: false, + StaticRange: false, + status: false, + statusbar: false, + StereoPannerNode: false, + stop: false, + Storage: false, + StorageEvent: false, + StorageManager: false, + styleMedia: false, + StyleSheet: false, + StyleSheetList: false, + SubtleCrypto: false, + SVGAElement: false, + SVGAngle: false, + SVGAnimatedAngle: false, + SVGAnimatedBoolean: false, + SVGAnimatedEnumeration: false, + SVGAnimatedInteger: false, + SVGAnimatedLength: false, + SVGAnimatedLengthList: false, + SVGAnimatedNumber: false, + SVGAnimatedNumberList: false, + SVGAnimatedPreserveAspectRatio: false, + SVGAnimatedRect: false, + SVGAnimatedString: false, + SVGAnimatedTransformList: false, + SVGAnimateElement: false, + SVGAnimateMotionElement: false, + SVGAnimateTransformElement: false, + SVGAnimationElement: false, + SVGCircleElement: false, + SVGClipPathElement: false, + SVGComponentTransferFunctionElement: false, + SVGDefsElement: false, + SVGDescElement: false, + SVGDiscardElement: false, + SVGElement: false, + SVGEllipseElement: false, + SVGFEBlendElement: false, + SVGFEColorMatrixElement: false, + SVGFEComponentTransferElement: false, + SVGFECompositeElement: false, + SVGFEConvolveMatrixElement: false, + SVGFEDiffuseLightingElement: false, + SVGFEDisplacementMapElement: false, + SVGFEDistantLightElement: false, + SVGFEDropShadowElement: false, + SVGFEFloodElement: false, + SVGFEFuncAElement: false, + SVGFEFuncBElement: false, + SVGFEFuncGElement: false, + SVGFEFuncRElement: false, + SVGFEGaussianBlurElement: false, + SVGFEImageElement: false, + SVGFEMergeElement: false, + SVGFEMergeNodeElement: false, + SVGFEMorphologyElement: false, + SVGFEOffsetElement: false, + SVGFEPointLightElement: false, + SVGFESpecularLightingElement: false, + SVGFESpotLightElement: false, + SVGFETileElement: false, + SVGFETurbulenceElement: false, + SVGFilterElement: false, + SVGForeignObjectElement: false, + SVGGElement: false, + SVGGeometryElement: false, + SVGGradientElement: false, + SVGGraphicsElement: false, + SVGImageElement: false, + SVGLength: false, + SVGLengthList: false, + SVGLinearGradientElement: false, + SVGLineElement: false, + SVGMarkerElement: false, + SVGMaskElement: false, + SVGMatrix: false, + SVGMetadataElement: false, + SVGMPathElement: false, + SVGNumber: false, + SVGNumberList: false, + SVGPathElement: false, + SVGPatternElement: false, + SVGPoint: false, + SVGPointList: false, + SVGPolygonElement: false, + SVGPolylineElement: false, + SVGPreserveAspectRatio: false, + SVGRadialGradientElement: false, + SVGRect: false, + SVGRectElement: false, + SVGScriptElement: false, + SVGSetElement: false, + SVGStopElement: false, + SVGStringList: false, + SVGStyleElement: false, + SVGSVGElement: false, + SVGSwitchElement: false, + SVGSymbolElement: false, + SVGTextContentElement: false, + SVGTextElement: false, + SVGTextPathElement: false, + SVGTextPositioningElement: false, + SVGTitleElement: false, + SVGTransform: false, + SVGTransformList: false, + SVGTSpanElement: false, + SVGUnitTypes: false, + SVGUseElement: false, + SVGViewElement: false, + TaskAttributionTiming: false, + Text: false, + TextDecoder: false, + TextEncoder: false, + TextEvent: false, + TextMetrics: false, + TextTrack: false, + TextTrackCue: false, + TextTrackCueList: false, + TextTrackList: false, + TimeRanges: false, + toolbar: false, + top: false, + Touch: false, + TouchEvent: false, + TouchList: false, + TrackEvent: false, + TransitionEvent: false, + TreeWalker: false, + UIEvent: false, + URL: false, + URLSearchParams: false, + ValidityState: false, + visualViewport: false, + VisualViewport: false, + VTTCue: false, + WaveShaperNode: false, + WebAssembly: false, + WebGL2RenderingContext: false, + WebGLActiveInfo: false, + WebGLBuffer: false, + WebGLContextEvent: false, + WebGLFramebuffer: false, + WebGLProgram: false, + WebGLQuery: false, + WebGLRenderbuffer: false, + WebGLRenderingContext: false, + WebGLSampler: false, + WebGLShader: false, + WebGLShaderPrecisionFormat: false, + WebGLSync: false, + WebGLTexture: false, + WebGLTransformFeedback: false, + WebGLUniformLocation: false, + WebGLVertexArrayObject: false, + WebSocket: false, + WheelEvent: false, + window: false, + Window: false, + Worker: false, + WritableStream: false, + XMLDocument: false, + XMLHttpRequest: false, + XMLHttpRequestEventTarget: false, + XMLHttpRequestUpload: false, + XMLSerializer: false, + XPathEvaluator: false, + XPathExpression: false, + XPathResult: false, + XSLTProcessor: false + }; + var worker = { + addEventListener: false, + applicationCache: false, + atob: false, + Blob: false, + BroadcastChannel: false, + btoa: false, + Cache: false, + caches: false, + clearInterval: false, + clearTimeout: false, + close: true, + console: false, + fetch: false, + FileReaderSync: false, + FormData: false, + Headers: false, + IDBCursor: false, + IDBCursorWithValue: false, + IDBDatabase: false, + IDBFactory: false, + IDBIndex: false, + IDBKeyRange: false, + IDBObjectStore: false, + IDBOpenDBRequest: false, + IDBRequest: false, + IDBTransaction: false, + IDBVersionChangeEvent: false, + ImageData: false, + importScripts: true, + indexedDB: false, + location: false, + MessageChannel: false, + MessagePort: false, + name: false, + navigator: false, + Notification: false, + onclose: true, + onconnect: true, + onerror: true, + onlanguagechange: true, + onmessage: true, + onoffline: true, + ononline: true, + onrejectionhandled: true, + onunhandledrejection: true, + performance: false, + Performance: false, + PerformanceEntry: false, + PerformanceMark: false, + PerformanceMeasure: false, + PerformanceNavigation: false, + PerformanceResourceTiming: false, + PerformanceTiming: false, + postMessage: true, + "Promise": false, + queueMicrotask: false, + removeEventListener: false, + Request: false, + Response: false, + self: true, + ServiceWorkerRegistration: false, + setInterval: false, + setTimeout: false, + TextDecoder: false, + TextEncoder: false, + URL: false, + URLSearchParams: false, + WebSocket: false, + Worker: false, + WorkerGlobalScope: false, + XMLHttpRequest: false + }; + var node$1 = { + __dirname: false, + __filename: false, + Buffer: false, + clearImmediate: false, + clearInterval: false, + clearTimeout: false, + console: false, + exports: true, + global: false, + "Intl": false, + module: false, + process: false, + queueMicrotask: false, + require: false, + setImmediate: false, + setInterval: false, + setTimeout: false, + TextDecoder: false, + TextEncoder: false, + URL: false, + URLSearchParams: false + }; + var commonjs = { + exports: true, + global: false, + module: false, + require: false + }; + var amd = { + define: false, + require: false + }; + var mocha = { + after: false, + afterEach: false, + before: false, + beforeEach: false, + context: false, + describe: false, + it: false, + mocha: false, + run: false, + setup: false, + specify: false, + suite: false, + suiteSetup: false, + suiteTeardown: false, + teardown: false, + test: false, + xcontext: false, + xdescribe: false, + xit: false, + xspecify: false + }; + var jasmine = { + afterAll: false, + afterEach: false, + beforeAll: false, + beforeEach: false, + describe: false, + expect: false, + fail: false, + fdescribe: false, + fit: false, + it: false, + jasmine: false, + pending: false, + runs: false, + spyOn: false, + spyOnProperty: false, + waits: false, + waitsFor: false, + xdescribe: false, + xit: false + }; + var jest = { + afterAll: false, + afterEach: false, + beforeAll: false, + beforeEach: false, + describe: false, + expect: false, + fdescribe: false, + fit: false, + it: false, + jest: false, + pit: false, + require: false, + test: false, + xdescribe: false, + xit: false, + xtest: false + }; + var qunit = { + asyncTest: false, + deepEqual: false, + equal: false, + expect: false, + module: false, + notDeepEqual: false, + notEqual: false, + notOk: false, + notPropEqual: false, + notStrictEqual: false, + ok: false, + propEqual: false, + QUnit: false, + raises: false, + start: false, + stop: false, + strictEqual: false, + test: false, + throws: false + }; + var phantomjs = { + console: true, + exports: true, + phantom: true, + require: true, + WebPage: true + }; + var couch = { + emit: false, + exports: false, + getRow: false, + log: false, + module: false, + provides: false, + require: false, + respond: false, + send: false, + start: false, + sum: false + }; + var rhino = { + defineClass: false, + deserialize: false, + gc: false, + help: false, + importClass: false, + importPackage: false, + java: false, + load: false, + loadClass: false, + Packages: false, + print: false, + quit: false, + readFile: false, + readUrl: false, + runCommand: false, + seal: false, + serialize: false, + spawn: false, + sync: false, + toint32: false, + version: false + }; + var nashorn = { + __DIR__: false, + __FILE__: false, + __LINE__: false, + com: false, + edu: false, + exit: false, + java: false, + Java: false, + javafx: false, + JavaImporter: false, + javax: false, + JSAdapter: false, + load: false, + loadWithNewGlobal: false, + org: false, + Packages: false, + print: false, + quit: false + }; + var wsh = { + ActiveXObject: true, + Enumerator: true, + GetObject: true, + ScriptEngine: true, + ScriptEngineBuildVersion: true, + ScriptEngineMajorVersion: true, + ScriptEngineMinorVersion: true, + VBArray: true, + WScript: true, + WSH: true, + XDomainRequest: true + }; + var jquery = { + $: false, + jQuery: false + }; + var yui = { + YAHOO: false, + YAHOO_config: false, + YUI: false, + YUI_config: false + }; + var shelljs = { + cat: false, + cd: false, + chmod: false, + config: false, + cp: false, + dirs: false, + echo: false, + env: false, + error: false, + exec: false, + exit: false, + find: false, + grep: false, + ln: false, + ls: false, + mkdir: false, + mv: false, + popd: false, + pushd: false, + pwd: false, + rm: false, + sed: false, + set: false, + target: false, + tempdir: false, + test: false, + touch: false, + which: false + }; + var prototypejs = { + $: false, + $$: false, + $A: false, + $break: false, + $continue: false, + $F: false, + $H: false, + $R: false, + $w: false, + Abstract: false, + Ajax: false, + Autocompleter: false, + Builder: false, + Class: false, + Control: false, + Draggable: false, + Draggables: false, + Droppables: false, + Effect: false, + Element: false, + Enumerable: false, + Event: false, + Field: false, + Form: false, + Hash: false, + Insertion: false, + ObjectRange: false, + PeriodicalExecuter: false, + Position: false, + Prototype: false, + Scriptaculous: false, + Selector: false, + Sortable: false, + SortableObserver: false, + Sound: false, + Template: false, + Toggle: false, + Try: false + }; + var meteor = { + _: false, + $: false, + Accounts: false, + AccountsClient: false, + AccountsCommon: false, + AccountsServer: false, + App: false, + Assets: false, + Blaze: false, + check: false, + Cordova: false, + DDP: false, + DDPRateLimiter: false, + DDPServer: false, + Deps: false, + EJSON: false, + Email: false, + HTTP: false, + Log: false, + Match: false, + Meteor: false, + Mongo: false, + MongoInternals: false, + Npm: false, + Package: false, + Plugin: false, + process: false, + Random: false, + ReactiveDict: false, + ReactiveVar: false, + Router: false, + ServiceConfiguration: false, + Session: false, + share: false, + Spacebars: false, + Template: false, + Tinytest: false, + Tracker: false, + UI: false, + Utils: false, + WebApp: false, + WebAppInternals: false + }; + var mongo = { + _isWindows: false, + _rand: false, + BulkWriteResult: false, + cat: false, + cd: false, + connect: false, + db: false, + getHostName: false, + getMemInfo: false, + hostname: false, + ISODate: false, + listFiles: false, + load: false, + ls: false, + md5sumFile: false, + mkdir: false, + Mongo: false, + NumberInt: false, + NumberLong: false, + ObjectId: false, + PlanCache: false, + print: false, + printjson: false, + pwd: false, + quit: false, + removeFile: false, + rs: false, + sh: false, + UUID: false, + version: false, + WriteResult: false + }; + var applescript = { + $: false, + Application: false, + Automation: false, + console: false, + delay: false, + Library: false, + ObjC: false, + ObjectSpecifier: false, + Path: false, + Progress: false, + Ref: false + }; + var serviceworker = { + addEventListener: false, + applicationCache: false, + atob: false, + Blob: false, + BroadcastChannel: false, + btoa: false, + Cache: false, + caches: false, + CacheStorage: false, + clearInterval: false, + clearTimeout: false, + Client: false, + clients: false, + Clients: false, + close: true, + console: false, + ExtendableEvent: false, + ExtendableMessageEvent: false, + fetch: false, + FetchEvent: false, + FileReaderSync: false, + FormData: false, + Headers: false, + IDBCursor: false, + IDBCursorWithValue: false, + IDBDatabase: false, + IDBFactory: false, + IDBIndex: false, + IDBKeyRange: false, + IDBObjectStore: false, + IDBOpenDBRequest: false, + IDBRequest: false, + IDBTransaction: false, + IDBVersionChangeEvent: false, + ImageData: false, + importScripts: false, + indexedDB: false, + location: false, + MessageChannel: false, + MessagePort: false, + name: false, + navigator: false, + Notification: false, + onclose: true, + onconnect: true, + onerror: true, + onfetch: true, + oninstall: true, + onlanguagechange: true, + onmessage: true, + onmessageerror: true, + onnotificationclick: true, + onnotificationclose: true, + onoffline: true, + ononline: true, + onpush: true, + onpushsubscriptionchange: true, + onrejectionhandled: true, + onsync: true, + onunhandledrejection: true, + performance: false, + Performance: false, + PerformanceEntry: false, + PerformanceMark: false, + PerformanceMeasure: false, + PerformanceNavigation: false, + PerformanceResourceTiming: false, + PerformanceTiming: false, + postMessage: true, + "Promise": false, + queueMicrotask: false, + registration: false, + removeEventListener: false, + Request: false, + Response: false, + self: false, + ServiceWorker: false, + ServiceWorkerContainer: false, + ServiceWorkerGlobalScope: false, + ServiceWorkerMessageEvent: false, + ServiceWorkerRegistration: false, + setInterval: false, + setTimeout: false, + skipWaiting: false, + TextDecoder: false, + TextEncoder: false, + URL: false, + URLSearchParams: false, + WebSocket: false, + WindowClient: false, + Worker: false, + WorkerGlobalScope: false, + XMLHttpRequest: false + }; + var atomtest = { + advanceClock: false, + fakeClearInterval: false, + fakeClearTimeout: false, + fakeSetInterval: false, + fakeSetTimeout: false, + resetTimeouts: false, + waitsForPromise: false + }; + var embertest = { + andThen: false, + click: false, + currentPath: false, + currentRouteName: false, + currentURL: false, + fillIn: false, + find: false, + findAll: false, + findWithAssert: false, + keyEvent: false, + pauseTest: false, + resumeTest: false, + triggerEvent: false, + visit: false, + wait: false + }; + var protractor = { + $: false, + $$: false, + browser: false, + by: false, + By: false, + DartObject: false, + element: false, + protractor: false + }; + var webextensions = { + browser: false, + chrome: false, + opr: false + }; + var greasemonkey = { + cloneInto: false, + createObjectIn: false, + exportFunction: false, + GM: false, + GM_addStyle: false, + GM_deleteValue: false, + GM_getResourceText: false, + GM_getResourceURL: false, + GM_getValue: false, + GM_info: false, + GM_listValues: false, + GM_log: false, + GM_openInTab: false, + GM_registerMenuCommand: false, + GM_setClipboard: false, + GM_setValue: false, + GM_xmlhttpRequest: false, + unsafeWindow: false + }; + var devtools = { + $: false, + $_: false, + $$: false, + $0: false, + $1: false, + $2: false, + $3: false, + $4: false, + $x: false, + chrome: false, + clear: false, + copy: false, + debug: false, + dir: false, + dirxml: false, + getEventListeners: false, + inspect: false, + keys: false, + monitor: false, + monitorEvents: false, + profile: false, + profileEnd: false, + queryObjects: false, + table: false, + undebug: false, + unmonitor: false, + unmonitorEvents: false, + values: false + }; + var globals = { + builtin: builtin, + es5: es5, + es2015: es2015, + es2017: es2017, + browser: browser$3, + worker: worker, + node: node$1, + commonjs: commonjs, + amd: amd, + mocha: mocha, + jasmine: jasmine, + jest: jest, + qunit: qunit, + phantomjs: phantomjs, + couch: couch, + rhino: rhino, + nashorn: nashorn, + wsh: wsh, + jquery: jquery, + yui: yui, + shelljs: shelljs, + prototypejs: prototypejs, + meteor: meteor, + mongo: mongo, + applescript: applescript, + serviceworker: serviceworker, + atomtest: atomtest, + embertest: embertest, + protractor: protractor, + "shared-node-browser": { + clearInterval: false, + clearTimeout: false, + console: false, + setInterval: false, + setTimeout: false, + URL: false, + URLSearchParams: false + }, + webextensions: webextensions, + greasemonkey: greasemonkey, + devtools: devtools + }; + + var globals$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + builtin: builtin, + es5: es5, + es2015: es2015, + es2017: es2017, + browser: browser$3, + worker: worker, + node: node$1, + commonjs: commonjs, + amd: amd, + mocha: mocha, + jasmine: jasmine, + jest: jest, + qunit: qunit, + phantomjs: phantomjs, + couch: couch, + rhino: rhino, + nashorn: nashorn, + wsh: wsh, + jquery: jquery, + yui: yui, + shelljs: shelljs, + prototypejs: prototypejs, + meteor: meteor, + mongo: mongo, + applescript: applescript, + serviceworker: serviceworker, + atomtest: atomtest, + embertest: embertest, + protractor: protractor, + webextensions: webextensions, + greasemonkey: greasemonkey, + devtools: devtools, + 'default': globals + }); + + var require$$0 = getCjsExportFromNamespace(globals$1); + + var globals$2 = require$$0; + + var cache = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.clear = clear; + exports.clearPath = clearPath; + exports.clearScope = clearScope; + exports.scope = exports.path = void 0; + let path = new WeakMap(); + exports.path = path; + let scope = new WeakMap(); + exports.scope = scope; + + function clear() { + clearPath(); + clearScope(); + } + + function clearPath() { + exports.path = path = new WeakMap(); + } + + function clearScope() { + exports.scope = scope = new WeakMap(); + } + }); + + unwrapExports(cache); + var cache_1 = cache.clear; + var cache_2 = cache.clearPath; + var cache_3 = cache.clearScope; + var cache_4 = cache.scope; + var cache_5 = cache.path; + + var scope = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = void 0; + + var _renamer = _interopRequireDefault(renamer); + + var _index = _interopRequireDefault(lib$a); + + var _binding = _interopRequireDefault(binding$1); + + var _globals = _interopRequireDefault(globals$2); + + var t = _interopRequireWildcard(lib$1); + + + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function gatherNodeParts(node, parts) { + switch (node == null ? void 0 : node.type) { + default: + if (t.isModuleDeclaration(node)) { + if (node.source) { + gatherNodeParts(node.source, parts); + } else if (node.specifiers && node.specifiers.length) { + for (const e of node.specifiers) gatherNodeParts(e, parts); + } else if (node.declaration) { + gatherNodeParts(node.declaration, parts); + } + } else if (t.isModuleSpecifier(node)) { + gatherNodeParts(node.local, parts); + } else if (t.isLiteral(node)) { + parts.push(node.value); + } + + break; + + case "MemberExpression": + case "OptionalMemberExpression": + case "JSXMemberExpression": + gatherNodeParts(node.object, parts); + gatherNodeParts(node.property, parts); + break; + + case "Identifier": + case "JSXIdentifier": + parts.push(node.name); + break; + + case "CallExpression": + case "OptionalCallExpression": + case "NewExpression": + gatherNodeParts(node.callee, parts); + break; + + case "ObjectExpression": + case "ObjectPattern": + for (const e of node.properties) { + gatherNodeParts(e, parts); + } + + break; + + case "SpreadElement": + case "RestElement": + gatherNodeParts(node.argument, parts); + break; + + case "ObjectProperty": + case "ObjectMethod": + case "ClassProperty": + case "ClassMethod": + case "ClassPrivateProperty": + case "ClassPrivateMethod": + gatherNodeParts(node.key, parts); + break; + + case "ThisExpression": + parts.push("this"); + break; + + case "Super": + parts.push("super"); + break; + + case "Import": + parts.push("import"); + break; + + case "DoExpression": + parts.push("do"); + break; + + case "YieldExpression": + parts.push("yield"); + gatherNodeParts(node.argument, parts); + break; + + case "AwaitExpression": + parts.push("await"); + gatherNodeParts(node.argument, parts); + break; + + case "AssignmentExpression": + gatherNodeParts(node.left, parts); + break; + + case "VariableDeclarator": + gatherNodeParts(node.id, parts); + break; + + case "FunctionExpression": + case "FunctionDeclaration": + case "ClassExpression": + case "ClassDeclaration": + gatherNodeParts(node.id, parts); + break; + + case "PrivateName": + gatherNodeParts(node.id, parts); + break; + + case "ParenthesizedExpression": + gatherNodeParts(node.expression, parts); + break; + + case "UnaryExpression": + case "UpdateExpression": + gatherNodeParts(node.argument, parts); + break; + + case "MetaProperty": + gatherNodeParts(node.meta, parts); + gatherNodeParts(node.property, parts); + break; + + case "JSXElement": + gatherNodeParts(node.openingElement, parts); + break; + + case "JSXOpeningElement": + parts.push(node.name); + break; + + case "JSXFragment": + gatherNodeParts(node.openingFragment, parts); + break; + + case "JSXOpeningFragment": + parts.push("Fragment"); + break; + + case "JSXNamespacedName": + gatherNodeParts(node.namespace, parts); + gatherNodeParts(node.name, parts); + break; + } + } + + const collectorVisitor = { + For(path) { + for (const key of t.FOR_INIT_KEYS) { + const declar = path.get(key); + + if (declar.isVar()) { + const parentScope = path.scope.getFunctionParent() || path.scope.getProgramParent(); + parentScope.registerBinding("var", declar); + } + } + }, + + Declaration(path) { + if (path.isBlockScoped()) return; + + if (path.isExportDeclaration() && path.get("declaration").isDeclaration()) { + return; + } + + const parent = path.scope.getFunctionParent() || path.scope.getProgramParent(); + parent.registerDeclaration(path); + }, + + ReferencedIdentifier(path, state) { + state.references.push(path); + }, + + ForXStatement(path, state) { + const left = path.get("left"); + + if (left.isPattern() || left.isIdentifier()) { + state.constantViolations.push(path); + } + }, + + ExportDeclaration: { + exit(path) { + const { + node, + scope + } = path; + const declar = node.declaration; + + if (t.isClassDeclaration(declar) || t.isFunctionDeclaration(declar)) { + const id = declar.id; + if (!id) return; + const binding = scope.getBinding(id.name); + if (binding) binding.reference(path); + } else if (t.isVariableDeclaration(declar)) { + for (const decl of declar.declarations) { + for (const name of Object.keys(t.getBindingIdentifiers(decl))) { + const binding = scope.getBinding(name); + if (binding) binding.reference(path); + } + } + } + } + + }, + + LabeledStatement(path) { + path.scope.getProgramParent().addGlobal(path.node); + path.scope.getBlockParent().registerDeclaration(path); + }, + + AssignmentExpression(path, state) { + state.assignments.push(path); + }, + + UpdateExpression(path, state) { + state.constantViolations.push(path); + }, + + UnaryExpression(path, state) { + if (path.node.operator === "delete") { + state.constantViolations.push(path); + } + }, + + BlockScoped(path) { + let scope = path.scope; + if (scope.path === path) scope = scope.parent; + const parent = scope.getBlockParent(); + parent.registerDeclaration(path); + + if (path.isClassDeclaration() && path.node.id) { + const id = path.node.id; + const name = id.name; + path.scope.bindings[name] = path.scope.parent.getBinding(name); + } + }, + + Block(path) { + const paths = path.get("body"); + + for (const bodyPath of paths) { + if (bodyPath.isFunctionDeclaration()) { + path.scope.getBlockParent().registerDeclaration(bodyPath); + } + } + }, + + CatchClause(path) { + path.scope.registerBinding("let", path); + }, + + Function(path) { + if (path.isFunctionExpression() && path.has("id") && !path.get("id").node[t.NOT_LOCAL_BINDING]) { + path.scope.registerBinding("local", path.get("id"), path); + } + + const params = path.get("params"); + + for (const param of params) { + path.scope.registerBinding("param", param); + } + }, + + ClassExpression(path) { + if (path.has("id") && !path.get("id").node[t.NOT_LOCAL_BINDING]) { + path.scope.registerBinding("local", path); + } + } + + }; + let uid = 0; + + class Scope { + constructor(path) { + const { + node + } = path; + + const cached = cache.scope.get(node); + + if ((cached == null ? void 0 : cached.path) === path) { + return cached; + } + + cache.scope.set(node, this); + + this.uid = uid++; + this.block = node; + this.path = path; + this.labels = new Map(); + this.inited = false; + } + + get parent() { + const parent = this.path.findParent(p => p.isScope()); + return parent == null ? void 0 : parent.scope; + } + + get parentBlock() { + return this.path.parent; + } + + get hub() { + return this.path.hub; + } + + traverse(node, opts, state) { + (0, _index.default)(node, opts, this, state, this.path); + } + + generateDeclaredUidIdentifier(name) { + const id = this.generateUidIdentifier(name); + this.push({ + id + }); + return t.cloneNode(id); + } + + generateUidIdentifier(name) { + return t.identifier(this.generateUid(name)); + } + + generateUid(name = "temp") { + name = t.toIdentifier(name).replace(/^_+/, "").replace(/[0-9]+$/g, ""); + let uid; + let i = 1; + + do { + uid = this._generateUid(name, i); + i++; + } while (this.hasLabel(uid) || this.hasBinding(uid) || this.hasGlobal(uid) || this.hasReference(uid)); + + const program = this.getProgramParent(); + program.references[uid] = true; + program.uids[uid] = true; + return uid; + } + + _generateUid(name, i) { + let id = name; + if (i > 1) id += i; + return `_${id}`; + } + + generateUidBasedOnNode(node, defaultName) { + const parts = []; + gatherNodeParts(node, parts); + let id = parts.join("$"); + id = id.replace(/^_/, "") || defaultName || "ref"; + return this.generateUid(id.slice(0, 20)); + } + + generateUidIdentifierBasedOnNode(node, defaultName) { + return t.identifier(this.generateUidBasedOnNode(node, defaultName)); + } + + isStatic(node) { + if (t.isThisExpression(node) || t.isSuper(node)) { + return true; + } + + if (t.isIdentifier(node)) { + const binding = this.getBinding(node.name); + + if (binding) { + return binding.constant; + } else { + return this.hasBinding(node.name); + } + } + + return false; + } + + maybeGenerateMemoised(node, dontPush) { + if (this.isStatic(node)) { + return null; + } else { + const id = this.generateUidIdentifierBasedOnNode(node); + + if (!dontPush) { + this.push({ + id + }); + return t.cloneNode(id); + } + + return id; + } + } + + checkBlockScopedCollisions(local, kind, name, id) { + if (kind === "param") return; + if (local.kind === "local") return; + const duplicate = kind === "let" || local.kind === "let" || local.kind === "const" || local.kind === "module" || local.kind === "param" && (kind === "let" || kind === "const"); + + if (duplicate) { + throw this.hub.buildError(id, `Duplicate declaration "${name}"`, TypeError); + } + } + + rename(oldName, newName, block) { + const binding = this.getBinding(oldName); + + if (binding) { + newName = newName || this.generateUidIdentifier(oldName).name; + return new _renamer.default(binding, oldName, newName).rename(block); + } + } + + _renameFromMap(map, oldName, newName, value) { + if (map[oldName]) { + map[newName] = value; + map[oldName] = null; + } + } + + dump() { + const sep = "-".repeat(60); + console.log(sep); + let scope = this; + + do { + console.log("#", scope.block.type); + + for (const name of Object.keys(scope.bindings)) { + const binding = scope.bindings[name]; + console.log(" -", name, { + constant: binding.constant, + references: binding.references, + violations: binding.constantViolations.length, + kind: binding.kind + }); + } + } while (scope = scope.parent); + + console.log(sep); + } + + toArray(node, i, allowArrayLike) { + if (t.isIdentifier(node)) { + const binding = this.getBinding(node.name); + + if ((binding == null ? void 0 : binding.constant) && binding.path.isGenericType("Array")) { + return node; + } + } + + if (t.isArrayExpression(node)) { + return node; + } + + if (t.isIdentifier(node, { + name: "arguments" + })) { + return t.callExpression(t.memberExpression(t.memberExpression(t.memberExpression(t.identifier("Array"), t.identifier("prototype")), t.identifier("slice")), t.identifier("call")), [node]); + } + + let helperName; + const args = [node]; + + if (i === true) { + helperName = "toConsumableArray"; + } else if (i) { + args.push(t.numericLiteral(i)); + helperName = "slicedToArray"; + } else { + helperName = "toArray"; + } + + if (allowArrayLike) { + args.unshift(this.hub.addHelper(helperName)); + helperName = "maybeArrayLike"; + } + + return t.callExpression(this.hub.addHelper(helperName), args); + } + + hasLabel(name) { + return !!this.getLabel(name); + } + + getLabel(name) { + return this.labels.get(name); + } + + registerLabel(path) { + this.labels.set(path.node.label.name, path); + } + + registerDeclaration(path) { + if (path.isLabeledStatement()) { + this.registerLabel(path); + } else if (path.isFunctionDeclaration()) { + this.registerBinding("hoisted", path.get("id"), path); + } else if (path.isVariableDeclaration()) { + const declarations = path.get("declarations"); + + for (const declar of declarations) { + this.registerBinding(path.node.kind, declar); + } + } else if (path.isClassDeclaration()) { + this.registerBinding("let", path); + } else if (path.isImportDeclaration()) { + const specifiers = path.get("specifiers"); + + for (const specifier of specifiers) { + this.registerBinding("module", specifier); + } + } else if (path.isExportDeclaration()) { + const declar = path.get("declaration"); + + if (declar.isClassDeclaration() || declar.isFunctionDeclaration() || declar.isVariableDeclaration()) { + this.registerDeclaration(declar); + } + } else { + this.registerBinding("unknown", path); + } + } + + buildUndefinedNode() { + return t.unaryExpression("void", t.numericLiteral(0), true); + } + + registerConstantViolation(path) { + const ids = path.getBindingIdentifiers(); + + for (const name of Object.keys(ids)) { + const binding = this.getBinding(name); + if (binding) binding.reassign(path); + } + } + + registerBinding(kind, path, bindingPath = path) { + if (!kind) throw new ReferenceError("no `kind`"); + + if (path.isVariableDeclaration()) { + const declarators = path.get("declarations"); + + for (const declar of declarators) { + this.registerBinding(kind, declar); + } + + return; + } + + const parent = this.getProgramParent(); + const ids = path.getOuterBindingIdentifiers(true); + + for (const name of Object.keys(ids)) { + parent.references[name] = true; + + for (const id of ids[name]) { + const local = this.getOwnBinding(name); + + if (local) { + if (local.identifier === id) continue; + this.checkBlockScopedCollisions(local, kind, name, id); + } + + if (local) { + this.registerConstantViolation(bindingPath); + } else { + this.bindings[name] = new _binding.default({ + identifier: id, + scope: this, + path: bindingPath, + kind: kind + }); + } + } + } + } + + addGlobal(node) { + this.globals[node.name] = node; + } + + hasUid(name) { + let scope = this; + + do { + if (scope.uids[name]) return true; + } while (scope = scope.parent); + + return false; + } + + hasGlobal(name) { + let scope = this; + + do { + if (scope.globals[name]) return true; + } while (scope = scope.parent); + + return false; + } + + hasReference(name) { + return !!this.getProgramParent().references[name]; + } + + isPure(node, constantsOnly) { + if (t.isIdentifier(node)) { + const binding = this.getBinding(node.name); + if (!binding) return false; + if (constantsOnly) return binding.constant; + return true; + } else if (t.isClass(node)) { + if (node.superClass && !this.isPure(node.superClass, constantsOnly)) { + return false; + } + + return this.isPure(node.body, constantsOnly); + } else if (t.isClassBody(node)) { + for (const method of node.body) { + if (!this.isPure(method, constantsOnly)) return false; + } + + return true; + } else if (t.isBinary(node)) { + return this.isPure(node.left, constantsOnly) && this.isPure(node.right, constantsOnly); + } else if (t.isArrayExpression(node)) { + for (const elem of node.elements) { + if (!this.isPure(elem, constantsOnly)) return false; + } + + return true; + } else if (t.isObjectExpression(node)) { + for (const prop of node.properties) { + if (!this.isPure(prop, constantsOnly)) return false; + } + + return true; + } else if (t.isMethod(node)) { + if (node.computed && !this.isPure(node.key, constantsOnly)) return false; + if (node.kind === "get" || node.kind === "set") return false; + return true; + } else if (t.isProperty(node)) { + if (node.computed && !this.isPure(node.key, constantsOnly)) return false; + return this.isPure(node.value, constantsOnly); + } else if (t.isUnaryExpression(node)) { + return this.isPure(node.argument, constantsOnly); + } else if (t.isTaggedTemplateExpression(node)) { + return t.matchesPattern(node.tag, "String.raw") && !this.hasBinding("String", true) && this.isPure(node.quasi, constantsOnly); + } else if (t.isTemplateLiteral(node)) { + for (const expression of node.expressions) { + if (!this.isPure(expression, constantsOnly)) return false; + } + + return true; + } else { + return t.isPureish(node); + } + } + + setData(key, val) { + return this.data[key] = val; + } + + getData(key) { + let scope = this; + + do { + const data = scope.data[key]; + if (data != null) return data; + } while (scope = scope.parent); + } + + removeData(key) { + let scope = this; + + do { + const data = scope.data[key]; + if (data != null) scope.data[key] = null; + } while (scope = scope.parent); + } + + init() { + if (!this.inited) { + this.inited = true; + this.crawl(); + } + } + + crawl() { + const path = this.path; + this.references = Object.create(null); + this.bindings = Object.create(null); + this.globals = Object.create(null); + this.uids = Object.create(null); + this.data = Object.create(null); + + if (path.isFunction()) { + if (path.isFunctionExpression() && path.has("id") && !path.get("id").node[t.NOT_LOCAL_BINDING]) { + this.registerBinding("local", path.get("id"), path); + } + + const params = path.get("params"); + + for (const param of params) { + this.registerBinding("param", param); + } + } + + const programParent = this.getProgramParent(); + if (programParent.crawling) return; + const state = { + references: [], + constantViolations: [], + assignments: [] + }; + this.crawling = true; + path.traverse(collectorVisitor, state); + this.crawling = false; + + for (const path of state.assignments) { + const ids = path.getBindingIdentifiers(); + + for (const name of Object.keys(ids)) { + if (path.scope.getBinding(name)) continue; + programParent.addGlobal(ids[name]); + } + + path.scope.registerConstantViolation(path); + } + + for (const ref of state.references) { + const binding = ref.scope.getBinding(ref.node.name); + + if (binding) { + binding.reference(ref); + } else { + programParent.addGlobal(ref.node); + } + } + + for (const path of state.constantViolations) { + path.scope.registerConstantViolation(path); + } + } + + push(opts) { + let path = this.path; + + if (!path.isBlockStatement() && !path.isProgram()) { + path = this.getBlockParent().path; + } + + if (path.isSwitchStatement()) { + path = (this.getFunctionParent() || this.getProgramParent()).path; + } + + if (path.isLoop() || path.isCatchClause() || path.isFunction()) { + path.ensureBlock(); + path = path.get("body"); + } + + const unique = opts.unique; + const kind = opts.kind || "var"; + const blockHoist = opts._blockHoist == null ? 2 : opts._blockHoist; + const dataKey = `declaration:${kind}:${blockHoist}`; + let declarPath = !unique && path.getData(dataKey); + + if (!declarPath) { + const declar = t.variableDeclaration(kind, []); + declar._blockHoist = blockHoist; + [declarPath] = path.unshiftContainer("body", [declar]); + if (!unique) path.setData(dataKey, declarPath); + } + + const declarator = t.variableDeclarator(opts.id, opts.init); + declarPath.node.declarations.push(declarator); + this.registerBinding(kind, declarPath.get("declarations").pop()); + } + + getProgramParent() { + let scope = this; + + do { + if (scope.path.isProgram()) { + return scope; + } + } while (scope = scope.parent); + + throw new Error("Couldn't find a Program"); + } + + getFunctionParent() { + let scope = this; + + do { + if (scope.path.isFunctionParent()) { + return scope; + } + } while (scope = scope.parent); + + return null; + } + + getBlockParent() { + let scope = this; + + do { + if (scope.path.isBlockParent()) { + return scope; + } + } while (scope = scope.parent); + + throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program..."); + } + + getAllBindings() { + const ids = Object.create(null); + let scope = this; + + do { + for (const key of Object.keys(scope.bindings)) { + if (key in ids === false) { + ids[key] = scope.bindings[key]; + } + } + + scope = scope.parent; + } while (scope); + + return ids; + } + + getAllBindingsOfKind() { + const ids = Object.create(null); + + for (const kind of arguments) { + let scope = this; + + do { + for (const name of Object.keys(scope.bindings)) { + const binding = scope.bindings[name]; + if (binding.kind === kind) ids[name] = binding; + } + + scope = scope.parent; + } while (scope); + } + + return ids; + } + + bindingIdentifierEquals(name, node) { + return this.getBindingIdentifier(name) === node; + } + + getBinding(name) { + let scope = this; + let previousPath; + + do { + const binding = scope.getOwnBinding(name); + + if (binding) { + var _previousPath; + + if (((_previousPath = previousPath) == null ? void 0 : _previousPath.isPattern()) && binding.kind !== "param") ; else { + return binding; + } + } + + previousPath = scope.path; + } while (scope = scope.parent); + } + + getOwnBinding(name) { + return this.bindings[name]; + } + + getBindingIdentifier(name) { + var _this$getBinding; + + return (_this$getBinding = this.getBinding(name)) == null ? void 0 : _this$getBinding.identifier; + } + + getOwnBindingIdentifier(name) { + const binding = this.bindings[name]; + return binding == null ? void 0 : binding.identifier; + } + + hasOwnBinding(name) { + return !!this.getOwnBinding(name); + } + + hasBinding(name, noGlobals) { + if (!name) return false; + if (this.hasOwnBinding(name)) return true; + if (this.parentHasBinding(name, noGlobals)) return true; + if (this.hasUid(name)) return true; + if (!noGlobals && Scope.globals.includes(name)) return true; + if (!noGlobals && Scope.contextVariables.includes(name)) return true; + return false; + } + + parentHasBinding(name, noGlobals) { + var _this$parent; + + return (_this$parent = this.parent) == null ? void 0 : _this$parent.hasBinding(name, noGlobals); + } + + moveBindingTo(name, scope) { + const info = this.getBinding(name); + + if (info) { + info.scope.removeOwnBinding(name); + info.scope = scope; + scope.bindings[name] = info; + } + } + + removeOwnBinding(name) { + delete this.bindings[name]; + } + + removeBinding(name) { + var _this$getBinding2; + + (_this$getBinding2 = this.getBinding(name)) == null ? void 0 : _this$getBinding2.scope.removeOwnBinding(name); + let scope = this; + + do { + if (scope.uids[name]) { + scope.uids[name] = false; + } + } while (scope = scope.parent); + } + + } + + exports.default = Scope; + Scope.globals = Object.keys(_globals.default.builtin); + Scope.contextVariables = ["arguments", "undefined", "Infinity", "NaN"]; + }); + + unwrapExports(scope); + + /* -*- 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. + */ + var 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. + */ + var 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; + }; + + var base64 = { + encode: encode, + decode: decode + }; + + /* -*- 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. + */ + + + + // 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. + */ + var encode$1 = 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. + */ + var decode$1 = 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; + }; + + var base64Vlq = { + encode: encode$1, + decode: decode$1 + }; + + var util$3 = createCommonjsModule(function (module, exports) { + /* -*- 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+))?(\S*)$/; + 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; + + /** + * 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. + */ + 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); + + var parts = path.split(/\/+/); + 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) === '/' || !!aPath.match(urlRegexp); + }; + + /** + * 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 = 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 mappingA.name - mappingB.name; + } + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * 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 = 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 mappingA.name - mappingB.name; + } + exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + + function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + 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; + }); + var util_1 = util$3.getArg; + var util_2 = util$3.urlParse; + var util_3 = util$3.urlGenerate; + var util_4 = util$3.normalize; + var util_5 = util$3.join; + var util_6 = util$3.isAbsolute; + var util_7 = util$3.relative; + var util_8 = util$3.toSetString; + var util_9 = util$3.fromSetString; + var util_10 = util$3.compareByOriginalPositions; + var util_11 = util$3.compareByGeneratedPositionsDeflated; + var util_12 = util$3.compareByGeneratedPositionsInflated; + + /* -*- 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 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$3.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$3.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$3.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(); + }; + + var ArraySet_1 = ArraySet; + + var arraySet = { + ArraySet: ArraySet_1 + }; + + /* -*- 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 + */ + + + + /** + * 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$3.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$3.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; + }; + + var MappingList_1 = MappingList; + + var mappingList = { + MappingList: MappingList_1 + }; + + /* -*- 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 ArraySet$1 = arraySet.ArraySet; + var MappingList$1 = mappingList.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$3.getArg(aArgs, 'file', null); + this._sourceRoot = util$3.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util$3.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet$1(); + this._names = new ArraySet$1(); + this._mappings = new MappingList$1(); + 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) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + 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$3.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 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$3.getArg(aArgs, 'generated'); + var original = util$3.getArg(aArgs, 'original', null); + var source = util$3.getArg(aArgs, 'source', null); + var name = util$3.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + 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$3.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$3.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$3.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$3.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet$1(); + var newNames = new ArraySet$1(); + + // 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$3.join(aSourceMapPath, mapping.source); + } + if (sourceRoot != null) { + mapping.source = util$3.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$3.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util$3.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') { + throw new Error( + '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 (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 { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + + /** + * 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$3.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$3.relative(aSourceRoot, source); + } + var key = util$3.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()); + }; + + var SourceMapGenerator_1 = SourceMapGenerator; + + var sourceMapGenerator = { + SourceMapGenerator: SourceMapGenerator_1 + }; + + var binarySearch = createCommonjsModule(function (module, exports) { + /* -*- 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; + }; + }); + var binarySearch_1 = binarySearch.GREATEST_LOWER_BOUND; + var binarySearch_2 = binarySearch.LEAST_UPPER_BOUND; + var binarySearch_3 = binarySearch.search; + + /* -*- 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`. + + /** + * 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$1(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$1(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) <= 0) { + i += 1; + swap$1(ary, i, j); + } + } + + swap$1(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); + } + } + + /** + * 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. + */ + var quickSort_1 = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); + }; + + var quickSort = { + quickSort: quickSort_1 + }; + + /* -*- 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 ArraySet$2 = arraySet.ArraySet; + + var quickSort$1 = quickSort.quickSort; + + function SourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap) + : new BasicSourceMapConsumer(sourceMap); + } + + SourceMapConsumer.fromSourceMap = function(aSourceMap) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap); + }; + + /** + * 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', { + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } + }); + + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + 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; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + if (source != null && sourceRoot != null) { + source = util$3.join(sourceRoot, source); + } + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + + /** + * 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. + * - column: Optional. the column number in the original source. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util$3.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$3.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util$3.getArg(aArgs, 'column', 0) + }; + + if (this.sourceRoot != null) { + needle.source = util$3.relative(this.sourceRoot, needle.source); + } + if (!this._sources.has(needle.source)) { + return []; + } + needle.source = this._sources.indexOf(needle.source); + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util$3.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$3.getArg(mapping, 'generatedLine', null), + column: util$3.getArg(mapping, 'generatedColumn', null), + lastColumn: util$3.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$3.getArg(mapping, 'generatedLine', null), + column: util$3.getArg(mapping, 'generatedColumn', null), + lastColumn: util$3.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + + var SourceMapConsumer_1 = 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 only 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;" + * } + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ + function BasicSourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + + var version = util$3.getArg(sourceMap, 'version'); + var sources = util$3.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$3.getArg(sourceMap, 'names', []); + var sourceRoot = util$3.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util$3.getArg(sourceMap, 'sourcesContent', null); + var mappings = util$3.getArg(sourceMap, 'mappings'); + var file = util$3.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); + } + + 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$3.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$3.isAbsolute(sourceRoot) && util$3.isAbsolute(source) + ? util$3.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$2.fromArray(names.map(String), true); + this._sources = ArraySet$2.fromArray(sources, true); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this.file = file; + } + + BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @returns BasicSourceMapConsumer + */ + BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet$2.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet$2.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + + // 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$1(smc.__originalMappings, util$3.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._sources.toArray().map(function (s) { + return this.sourceRoot != null ? util$3.join(this.sourceRoot, s) : s; + }, this); + } + }); + + /** + * 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). + */ + 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; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + 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'); + } + + cachedSegments[str] = segment; + } + + // 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') { + originalMappings.push(mapping); + } + } + } + + quickSort$1(generatedMappings, util$3.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort$1(originalMappings, util$3.compareByOriginalPositions); + this.__originalMappings = 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. + * - column: The column number in the generated source. + * - 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. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ + BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util$3.getArg(aArgs, 'line'), + generatedColumn: util$3.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util$3.compareByGeneratedPositionsDeflated, + util$3.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util$3.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + if (this.sourceRoot != null) { + source = util$3.join(this.sourceRoot, source); + } + } + var name = util$3.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util$3.getArg(mapping, 'originalLine', null), + column: util$3.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; + } + + if (this.sourceRoot != null) { + aSource = util$3.relative(this.sourceRoot, aSource); + } + + if (this._sources.has(aSource)) { + return this.sourcesContent[this._sources.indexOf(aSource)]; + } + + var url; + if (this.sourceRoot != null + && (url = util$3.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 = aSource.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("/" + aSource)) { + return this.sourcesContent[this._sources.indexOf("/" + aSource)]; + } + } + + // 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('"' + 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. + * - column: The column number in the original source. + * - 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. + * - column: The column number in the generated source, or null. + */ + BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util$3.getArg(aArgs, 'source'); + if (this.sourceRoot != null) { + source = util$3.relative(this.sourceRoot, source); + } + if (!this._sources.has(source)) { + return { + line: null, + column: null, + lastColumn: null + }; + } + source = this._sources.indexOf(source); + + var needle = { + source: source, + originalLine: util$3.getArg(aArgs, 'line'), + originalColumn: util$3.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util$3.compareByOriginalPositions, + util$3.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util$3.getArg(mapping, 'generatedLine', null), + column: util$3.getArg(mapping, 'generatedColumn', null), + lastColumn: util$3.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + + var BasicSourceMapConsumer_1 = 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 only 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;" + * } + * }], + * } + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ + function IndexedSourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + + var version = util$3.getArg(sourceMap, 'version'); + var sections = util$3.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet$2(); + this._names = new ArraySet$2(); + + 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$3.getArg(s, 'offset'); + var offsetLine = util$3.getArg(offset, 'line'); + var offsetColumn = util$3.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$3.getArg(s, 'map')) + } + }); + } + + 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. + * - column: The column number in the generated source. + * + * 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. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ + IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util$3.getArg(aArgs, 'line'), + generatedColumn: util$3.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) { + 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. + * - column: The column number in the original source. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + 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.sources.indexOf(util$3.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 (section.consumer.sourceRoot !== null) { + source = util$3.join(section.consumer.sourceRoot, source); + } + this._sources.add(source); + source = this._sources.indexOf(source); + + var 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$1(this.__generatedMappings, util$3.compareByGeneratedPositionsDeflated); + quickSort$1(this.__originalMappings, util$3.compareByOriginalPositions); + }; + + var IndexedSourceMapConsumer_1 = IndexedSourceMapConsumer; + + var sourceMapConsumer = { + SourceMapConsumer: SourceMapConsumer_1, + BasicSourceMapConsumer: BasicSourceMapConsumer_1, + IndexedSourceMapConsumer: IndexedSourceMapConsumer_1 + }; + + /* -*- 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$1 = sourceMapGenerator.SourceMapGenerator; + + + // 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$3.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$3.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$3.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$3.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$1(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 }; + }; + + var SourceNode_1 = SourceNode; + + var sourceNode = { + SourceNode: SourceNode_1 + }; + + /* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ + var SourceMapGenerator$2 = sourceMapGenerator.SourceMapGenerator; + var SourceMapConsumer$1 = sourceMapConsumer.SourceMapConsumer; + var SourceNode$1 = sourceNode.SourceNode; + + var sourceMap = { + SourceMapGenerator: SourceMapGenerator$2, + SourceMapConsumer: SourceMapConsumer$1, + SourceNode: SourceNode$1 + }; + + var sourceMap$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = void 0; + + var _sourceMap = _interopRequireDefault(sourceMap); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + class SourceMap { + constructor(opts, code) { + this._cachedMap = null; + this._code = code; + this._opts = opts; + this._rawMappings = []; + } + + get() { + if (!this._cachedMap) { + const map = this._cachedMap = new _sourceMap.default.SourceMapGenerator({ + sourceRoot: this._opts.sourceRoot + }); + const code = this._code; + + if (typeof code === "string") { + map.setSourceContent(this._opts.sourceFileName.replace(/\\/g, "/"), code); + } else if (typeof code === "object") { + Object.keys(code).forEach(sourceFileName => { + map.setSourceContent(sourceFileName.replace(/\\/g, "/"), code[sourceFileName]); + }); + } + + this._rawMappings.forEach(mapping => map.addMapping(mapping), map); + } + + return this._cachedMap.toJSON(); + } + + getRawMappings() { + return this._rawMappings.slice(); + } + + mark(generatedLine, generatedColumn, line, column, identifierName, filename, force) { + if (this._lastGenLine !== generatedLine && line === null) return; + + if (!force && this._lastGenLine === generatedLine && this._lastSourceLine === line && this._lastSourceColumn === column) { + return; + } + + this._cachedMap = null; + this._lastGenLine = generatedLine; + this._lastSourceLine = line; + this._lastSourceColumn = column; + + this._rawMappings.push({ + name: identifierName || undefined, + generated: { + line: generatedLine, + column: generatedColumn + }, + source: line == null ? undefined : (filename || this._opts.sourceFileName).replace(/\\/g, "/"), + original: line == null ? undefined : { + line: line, + column: column + } + }); + } + + } + + exports.default = SourceMap; + }); + + unwrapExports(sourceMap$1); + + var buffer = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = void 0; + const SPACES_RE = /^[ \t]+$/; + + class Buffer { + constructor(map) { + this._map = null; + this._buf = []; + this._last = ""; + this._queue = []; + this._position = { + line: 1, + column: 0 + }; + this._sourcePosition = { + identifierName: null, + line: null, + column: null, + filename: null + }; + this._disallowedPop = null; + this._map = map; + } + + get() { + this._flush(); + + const map = this._map; + const result = { + code: this._buf.join("").trimRight(), + map: null, + rawMappings: map == null ? void 0 : map.getRawMappings() + }; + + if (map) { + Object.defineProperty(result, "map", { + configurable: true, + enumerable: true, + + get() { + return this.map = map.get(); + }, + + set(value) { + Object.defineProperty(this, "map", { + value, + writable: true + }); + } + + }); + } + + return result; + } + + append(str) { + this._flush(); + + const { + line, + column, + filename, + identifierName, + force + } = this._sourcePosition; + + this._append(str, line, column, identifierName, filename, force); + } + + queue(str) { + if (str === "\n") { + while (this._queue.length > 0 && SPACES_RE.test(this._queue[0][0])) { + this._queue.shift(); + } + } + + const { + line, + column, + filename, + identifierName, + force + } = this._sourcePosition; + + this._queue.unshift([str, line, column, identifierName, filename, force]); + } + + _flush() { + let item; + + while (item = this._queue.pop()) this._append(...item); + } + + _append(str, line, column, identifierName, filename, force) { + this._buf.push(str); + + this._last = str[str.length - 1]; + let i = str.indexOf("\n"); + let last = 0; + + if (i !== 0) { + this._mark(line, column, identifierName, filename, force); + } + + while (i !== -1) { + this._position.line++; + this._position.column = 0; + last = i + 1; + + if (last < str.length) { + this._mark(++line, 0, identifierName, filename, force); + } + + i = str.indexOf("\n", last); + } + + this._position.column += str.length - last; + } + + _mark(line, column, identifierName, filename, force) { + var _this$_map; + + (_this$_map = this._map) == null ? void 0 : _this$_map.mark(this._position.line, this._position.column, line, column, identifierName, filename, force); + } + + removeTrailingNewline() { + if (this._queue.length > 0 && this._queue[0][0] === "\n") { + this._queue.shift(); + } + } + + removeLastSemicolon() { + if (this._queue.length > 0 && this._queue[0][0] === ";") { + this._queue.shift(); + } + } + + endsWith(suffix) { + if (suffix.length === 1) { + let last; + + if (this._queue.length > 0) { + const str = this._queue[0][0]; + last = str[str.length - 1]; + } else { + last = this._last; + } + + return last === suffix; + } + + const end = this._last + this._queue.reduce((acc, item) => item[0] + acc, ""); + + if (suffix.length <= end.length) { + return end.slice(-suffix.length) === suffix; + } + + return false; + } + + hasContent() { + return this._queue.length > 0 || !!this._last; + } + + exactSource(loc, cb) { + this.source("start", loc, true); + cb(); + this.source("end", loc); + + this._disallowPop("start", loc); + } + + source(prop, loc, force) { + if (prop && !loc) return; + + this._normalizePosition(prop, loc, this._sourcePosition, force); + } + + withSource(prop, loc, cb) { + if (!this._map) return cb(); + const originalLine = this._sourcePosition.line; + const originalColumn = this._sourcePosition.column; + const originalFilename = this._sourcePosition.filename; + const originalIdentifierName = this._sourcePosition.identifierName; + this.source(prop, loc); + cb(); + + if ((!this._sourcePosition.force || this._sourcePosition.line !== originalLine || this._sourcePosition.column !== originalColumn || this._sourcePosition.filename !== originalFilename) && (!this._disallowedPop || this._disallowedPop.line !== originalLine || this._disallowedPop.column !== originalColumn || this._disallowedPop.filename !== originalFilename)) { + this._sourcePosition.line = originalLine; + this._sourcePosition.column = originalColumn; + this._sourcePosition.filename = originalFilename; + this._sourcePosition.identifierName = originalIdentifierName; + this._sourcePosition.force = false; + this._disallowedPop = null; + } + } + + _disallowPop(prop, loc) { + if (prop && !loc) return; + this._disallowedPop = this._normalizePosition(prop, loc); + } + + _normalizePosition(prop, loc, targetObj, force) { + const pos = loc ? loc[prop] : null; + + if (targetObj === undefined) { + targetObj = { + identifierName: null, + line: null, + column: null, + filename: null, + force: false + }; + } + + const origLine = targetObj.line; + const origColumn = targetObj.column; + const origFilename = targetObj.filename; + targetObj.identifierName = prop === "start" && (loc == null ? void 0 : loc.identifierName) || null; + targetObj.line = pos == null ? void 0 : pos.line; + targetObj.column = pos == null ? void 0 : pos.column; + targetObj.filename = loc == null ? void 0 : loc.filename; + + if (force || targetObj.line !== origLine || targetObj.column !== origColumn || targetObj.filename !== origFilename) { + targetObj.force = force; + } + + return targetObj; + } + + getCurrentColumn() { + const extra = this._queue.reduce((acc, item) => item[0] + acc, ""); + + const lastIndex = extra.lastIndexOf("\n"); + return lastIndex === -1 ? this._position.column + extra.length : extra.length - 1 - lastIndex; + } + + getCurrentLine() { + const extra = this._queue.reduce((acc, item) => item[0] + acc, ""); + + let count = 0; + + for (let i = 0; i < extra.length; i++) { + if (extra[i] === "\n") count++; + } + + return this._position.line + count; + } + + } + + exports.default = Buffer; + }); + + unwrapExports(buffer); + + var whitespace = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.list = exports.nodes = void 0; + + var t = _interopRequireWildcard(lib$1); + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + function crawl(node, state = {}) { + if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) { + crawl(node.object, state); + if (node.computed) crawl(node.property, state); + } else if (t.isBinary(node) || t.isAssignmentExpression(node)) { + crawl(node.left, state); + crawl(node.right, state); + } else if (t.isCallExpression(node) || t.isOptionalCallExpression(node)) { + state.hasCall = true; + crawl(node.callee, state); + } else if (t.isFunction(node)) { + state.hasFunction = true; + } else if (t.isIdentifier(node)) { + state.hasHelper = state.hasHelper || isHelper(node.callee); + } + + return state; + } + + function isHelper(node) { + if (t.isMemberExpression(node)) { + return isHelper(node.object) || isHelper(node.property); + } else if (t.isIdentifier(node)) { + return node.name === "require" || node.name[0] === "_"; + } else if (t.isCallExpression(node)) { + return isHelper(node.callee); + } else if (t.isBinary(node) || t.isAssignmentExpression(node)) { + return t.isIdentifier(node.left) && isHelper(node.left) || isHelper(node.right); + } else { + return false; + } + } + + function isType(node) { + return t.isLiteral(node) || t.isObjectExpression(node) || t.isArrayExpression(node) || t.isIdentifier(node) || t.isMemberExpression(node); + } + + const nodes = { + AssignmentExpression(node) { + const state = crawl(node.right); + + if (state.hasCall && state.hasHelper || state.hasFunction) { + return { + before: state.hasFunction, + after: true + }; + } + }, + + SwitchCase(node, parent) { + return { + before: node.consequent.length || parent.cases[0] === node, + after: !node.consequent.length && parent.cases[parent.cases.length - 1] === node + }; + }, + + LogicalExpression(node) { + if (t.isFunction(node.left) || t.isFunction(node.right)) { + return { + after: true + }; + } + }, + + Literal(node) { + if (node.value === "use strict") { + return { + after: true + }; + } + }, + + CallExpression(node) { + if (t.isFunction(node.callee) || isHelper(node)) { + return { + before: true, + after: true + }; + } + }, + + OptionalCallExpression(node) { + if (t.isFunction(node.callee)) { + return { + before: true, + after: true + }; + } + }, + + VariableDeclaration(node) { + for (let i = 0; i < node.declarations.length; i++) { + const declar = node.declarations[i]; + let enabled = isHelper(declar.id) && !isType(declar.init); + + if (!enabled) { + const state = crawl(declar.init); + enabled = isHelper(declar.init) && state.hasCall || state.hasFunction; + } + + if (enabled) { + return { + before: true, + after: true + }; + } + } + }, + + IfStatement(node) { + if (t.isBlockStatement(node.consequent)) { + return { + before: true, + after: true + }; + } + } + + }; + exports.nodes = nodes; + + nodes.ObjectProperty = nodes.ObjectTypeProperty = nodes.ObjectMethod = function (node, parent) { + if (parent.properties[0] === node) { + return { + before: true + }; + } + }; + + nodes.ObjectTypeCallProperty = function (node, parent) { + var _parent$properties; + + if (parent.callProperties[0] === node && !((_parent$properties = parent.properties) == null ? void 0 : _parent$properties.length)) { + return { + before: true + }; + } + }; + + nodes.ObjectTypeIndexer = function (node, parent) { + var _parent$properties2, _parent$callPropertie; + + if (parent.indexers[0] === node && !((_parent$properties2 = parent.properties) == null ? void 0 : _parent$properties2.length) && !((_parent$callPropertie = parent.callProperties) == null ? void 0 : _parent$callPropertie.length)) { + return { + before: true + }; + } + }; + + nodes.ObjectTypeInternalSlot = function (node, parent) { + var _parent$properties3, _parent$callPropertie2, _parent$indexers; + + if (parent.internalSlots[0] === node && !((_parent$properties3 = parent.properties) == null ? void 0 : _parent$properties3.length) && !((_parent$callPropertie2 = parent.callProperties) == null ? void 0 : _parent$callPropertie2.length) && !((_parent$indexers = parent.indexers) == null ? void 0 : _parent$indexers.length)) { + return { + before: true + }; + } + }; + + const list = { + VariableDeclaration(node) { + return node.declarations.map(decl => decl.init); + }, + + ArrayExpression(node) { + return node.elements; + }, + + ObjectExpression(node) { + return node.properties; + } + + }; + exports.list = list; + [["Function", true], ["Class", true], ["Loop", true], ["LabeledStatement", true], ["SwitchStatement", true], ["TryStatement", true]].forEach(function ([type, amounts]) { + if (typeof amounts === "boolean") { + amounts = { + after: amounts, + before: amounts + }; + } + + [type].concat(t.FLIPPED_ALIAS_KEYS[type] || []).forEach(function (type) { + nodes[type] = function () { + return amounts; + }; + }); + }); + }); + + unwrapExports(whitespace); + var whitespace_1 = whitespace.list; + var whitespace_2 = whitespace.nodes; + + var parentheses = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.NullableTypeAnnotation = NullableTypeAnnotation; + exports.FunctionTypeAnnotation = FunctionTypeAnnotation; + exports.UpdateExpression = UpdateExpression; + exports.ObjectExpression = ObjectExpression; + exports.DoExpression = DoExpression; + exports.Binary = Binary; + exports.IntersectionTypeAnnotation = exports.UnionTypeAnnotation = UnionTypeAnnotation; + exports.TSAsExpression = TSAsExpression; + exports.TSTypeAssertion = TSTypeAssertion; + exports.TSIntersectionType = exports.TSUnionType = TSUnionType; + exports.TSInferType = TSInferType; + exports.BinaryExpression = BinaryExpression; + exports.SequenceExpression = SequenceExpression; + exports.AwaitExpression = exports.YieldExpression = YieldExpression; + exports.ClassExpression = ClassExpression; + exports.UnaryLike = UnaryLike; + exports.FunctionExpression = FunctionExpression; + exports.ArrowFunctionExpression = ArrowFunctionExpression; + exports.ConditionalExpression = ConditionalExpression; + exports.OptionalCallExpression = exports.OptionalMemberExpression = OptionalMemberExpression; + exports.AssignmentExpression = AssignmentExpression; + exports.LogicalExpression = LogicalExpression; + + var t = _interopRequireWildcard(lib$1); + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + const PRECEDENCE = { + "||": 0, + "??": 0, + "&&": 1, + "|": 2, + "^": 3, + "&": 4, + "==": 5, + "===": 5, + "!=": 5, + "!==": 5, + "<": 6, + ">": 6, + "<=": 6, + ">=": 6, + in: 6, + instanceof: 6, + ">>": 7, + "<<": 7, + ">>>": 7, + "+": 8, + "-": 8, + "*": 9, + "/": 9, + "%": 9, + "**": 10 + }; + + const isClassExtendsClause = (node, parent) => (t.isClassDeclaration(parent) || t.isClassExpression(parent)) && parent.superClass === node; + + const hasPostfixPart = (node, parent) => (t.isMemberExpression(parent) || t.isOptionalMemberExpression(parent)) && parent.object === node || (t.isCallExpression(parent) || t.isOptionalCallExpression(parent) || t.isNewExpression(parent)) && parent.callee === node || t.isTaggedTemplateExpression(parent) && parent.tag === node || t.isTSNonNullExpression(parent); + + function NullableTypeAnnotation(node, parent) { + return t.isArrayTypeAnnotation(parent); + } + + function FunctionTypeAnnotation(node, parent, printStack) { + return t.isUnionTypeAnnotation(parent) || t.isIntersectionTypeAnnotation(parent) || t.isArrayTypeAnnotation(parent) || t.isTypeAnnotation(parent) && t.isArrowFunctionExpression(printStack[printStack.length - 3]); + } + + function UpdateExpression(node, parent) { + return hasPostfixPart(node, parent) || isClassExtendsClause(node, parent); + } + + function ObjectExpression(node, parent, printStack) { + return isFirstInStatement(printStack, { + considerArrow: true + }); + } + + function DoExpression(node, parent, printStack) { + return isFirstInStatement(printStack); + } + + function Binary(node, parent) { + if (node.operator === "**" && t.isBinaryExpression(parent, { + operator: "**" + })) { + return parent.left === node; + } + + if (isClassExtendsClause(node, parent)) { + return true; + } + + if (hasPostfixPart(node, parent) || t.isUnaryLike(parent) || t.isAwaitExpression(parent)) { + return true; + } + + if (t.isBinary(parent)) { + const parentOp = parent.operator; + const parentPos = PRECEDENCE[parentOp]; + const nodeOp = node.operator; + const nodePos = PRECEDENCE[nodeOp]; + + if (parentPos === nodePos && parent.right === node && !t.isLogicalExpression(parent) || parentPos > nodePos) { + return true; + } + } + } + + function UnionTypeAnnotation(node, parent) { + return t.isArrayTypeAnnotation(parent) || t.isNullableTypeAnnotation(parent) || t.isIntersectionTypeAnnotation(parent) || t.isUnionTypeAnnotation(parent); + } + + function TSAsExpression() { + return true; + } + + function TSTypeAssertion() { + return true; + } + + function TSUnionType(node, parent) { + return t.isTSArrayType(parent) || t.isTSOptionalType(parent) || t.isTSIntersectionType(parent) || t.isTSUnionType(parent) || t.isTSRestType(parent); + } + + function TSInferType(node, parent) { + return t.isTSArrayType(parent) || t.isTSOptionalType(parent); + } + + function BinaryExpression(node, parent) { + return node.operator === "in" && (t.isVariableDeclarator(parent) || t.isFor(parent)); + } + + function SequenceExpression(node, parent) { + if (t.isForStatement(parent) || t.isThrowStatement(parent) || t.isReturnStatement(parent) || t.isIfStatement(parent) && parent.test === node || t.isWhileStatement(parent) && parent.test === node || t.isForInStatement(parent) && parent.right === node || t.isSwitchStatement(parent) && parent.discriminant === node || t.isExpressionStatement(parent) && parent.expression === node) { + return false; + } + + return true; + } + + function YieldExpression(node, parent) { + return t.isBinary(parent) || t.isUnaryLike(parent) || hasPostfixPart(node, parent) || t.isAwaitExpression(parent) && t.isYieldExpression(node) || t.isConditionalExpression(parent) && node === parent.test || isClassExtendsClause(node, parent); + } + + function ClassExpression(node, parent, printStack) { + return isFirstInStatement(printStack, { + considerDefaultExports: true + }); + } + + function UnaryLike(node, parent) { + return hasPostfixPart(node, parent) || t.isBinaryExpression(parent, { + operator: "**", + left: node + }) || isClassExtendsClause(node, parent); + } + + function FunctionExpression(node, parent, printStack) { + return isFirstInStatement(printStack, { + considerDefaultExports: true + }); + } + + function ArrowFunctionExpression(node, parent) { + return t.isExportDeclaration(parent) || ConditionalExpression(node, parent); + } + + function ConditionalExpression(node, parent) { + if (t.isUnaryLike(parent) || t.isBinary(parent) || t.isConditionalExpression(parent, { + test: node + }) || t.isAwaitExpression(parent) || t.isTSTypeAssertion(parent) || t.isTSAsExpression(parent)) { + return true; + } + + return UnaryLike(node, parent); + } + + function OptionalMemberExpression(node, parent) { + return t.isCallExpression(parent, { + callee: node + }) || t.isMemberExpression(parent, { + object: node + }); + } + + function AssignmentExpression(node, parent, printStack) { + if (t.isObjectPattern(node.left)) { + return true; + } else { + return ConditionalExpression(node, parent); + } + } + + function LogicalExpression(node, parent) { + switch (node.operator) { + case "||": + if (!t.isLogicalExpression(parent)) return false; + return parent.operator === "??" || parent.operator === "&&"; + + case "&&": + return t.isLogicalExpression(parent, { + operator: "??" + }); + + case "??": + return t.isLogicalExpression(parent) && parent.operator !== "??"; + } + } + + function isFirstInStatement(printStack, { + considerArrow = false, + considerDefaultExports = false + } = {}) { + let i = printStack.length - 1; + let node = printStack[i]; + i--; + let parent = printStack[i]; + + while (i >= 0) { + if (t.isExpressionStatement(parent, { + expression: node + }) || considerDefaultExports && t.isExportDefaultDeclaration(parent, { + declaration: node + }) || considerArrow && t.isArrowFunctionExpression(parent, { + body: node + })) { + return true; + } + + if (hasPostfixPart(node, parent) && !t.isNewExpression(parent) || t.isSequenceExpression(parent) && parent.expressions[0] === node || t.isConditional(parent, { + test: node + }) || t.isBinary(parent, { + left: node + }) || t.isAssignmentExpression(parent, { + left: node + })) { + node = parent; + i--; + parent = printStack[i]; + } else { + return false; + } + } + + return false; + } + }); + + unwrapExports(parentheses); + var parentheses_1 = parentheses.NullableTypeAnnotation; + var parentheses_2 = parentheses.FunctionTypeAnnotation; + var parentheses_3 = parentheses.UpdateExpression; + var parentheses_4 = parentheses.ObjectExpression; + var parentheses_5 = parentheses.DoExpression; + var parentheses_6 = parentheses.Binary; + var parentheses_7 = parentheses.IntersectionTypeAnnotation; + var parentheses_8 = parentheses.UnionTypeAnnotation; + var parentheses_9 = parentheses.TSAsExpression; + var parentheses_10 = parentheses.TSTypeAssertion; + var parentheses_11 = parentheses.TSIntersectionType; + var parentheses_12 = parentheses.TSUnionType; + var parentheses_13 = parentheses.TSInferType; + var parentheses_14 = parentheses.BinaryExpression; + var parentheses_15 = parentheses.SequenceExpression; + var parentheses_16 = parentheses.AwaitExpression; + var parentheses_17 = parentheses.YieldExpression; + var parentheses_18 = parentheses.ClassExpression; + var parentheses_19 = parentheses.UnaryLike; + var parentheses_20 = parentheses.FunctionExpression; + var parentheses_21 = parentheses.ArrowFunctionExpression; + var parentheses_22 = parentheses.ConditionalExpression; + var parentheses_23 = parentheses.OptionalCallExpression; + var parentheses_24 = parentheses.OptionalMemberExpression; + var parentheses_25 = parentheses.AssignmentExpression; + var parentheses_26 = parentheses.LogicalExpression; + + var node$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.needsWhitespace = needsWhitespace; + exports.needsWhitespaceBefore = needsWhitespaceBefore; + exports.needsWhitespaceAfter = needsWhitespaceAfter; + exports.needsParens = needsParens; + + var whitespace$1 = _interopRequireWildcard(whitespace); + + var parens = _interopRequireWildcard(parentheses); + + var t = _interopRequireWildcard(lib$1); + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + function expandAliases(obj) { + const newObj = {}; + + function add(type, func) { + const fn = newObj[type]; + newObj[type] = fn ? function (node, parent, stack) { + const result = fn(node, parent, stack); + return result == null ? func(node, parent, stack) : result; + } : func; + } + + for (const type of Object.keys(obj)) { + const aliases = t.FLIPPED_ALIAS_KEYS[type]; + + if (aliases) { + for (const alias of aliases) { + add(alias, obj[type]); + } + } else { + add(type, obj[type]); + } + } + + return newObj; + } + + const expandedParens = expandAliases(parens); + const expandedWhitespaceNodes = expandAliases(whitespace$1.nodes); + const expandedWhitespaceList = expandAliases(whitespace$1.list); + + function find(obj, node, parent, printStack) { + const fn = obj[node.type]; + return fn ? fn(node, parent, printStack) : null; + } + + function isOrHasCallExpression(node) { + if (t.isCallExpression(node)) { + return true; + } + + return t.isMemberExpression(node) && isOrHasCallExpression(node.object); + } + + function needsWhitespace(node, parent, type) { + if (!node) return 0; + + if (t.isExpressionStatement(node)) { + node = node.expression; + } + + let linesInfo = find(expandedWhitespaceNodes, node, parent); + + if (!linesInfo) { + const items = find(expandedWhitespaceList, node, parent); + + if (items) { + for (let i = 0; i < items.length; i++) { + linesInfo = needsWhitespace(items[i], node, type); + if (linesInfo) break; + } + } + } + + if (typeof linesInfo === "object" && linesInfo !== null) { + return linesInfo[type] || 0; + } + + return 0; + } + + function needsWhitespaceBefore(node, parent) { + return needsWhitespace(node, parent, "before"); + } + + function needsWhitespaceAfter(node, parent) { + return needsWhitespace(node, parent, "after"); + } + + function needsParens(node, parent, printStack) { + if (!parent) return false; + + if (t.isNewExpression(parent) && parent.callee === node) { + if (isOrHasCallExpression(node)) return true; + } + + return find(expandedParens, node, parent, printStack); + } + }); + + unwrapExports(node$2); + var node_1$1 = node$2.needsWhitespace; + var node_2$1 = node$2.needsWhitespaceBefore; + var node_3$1 = node$2.needsWhitespaceAfter; + var node_4$1 = node$2.needsParens; + + var templateLiterals = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.TaggedTemplateExpression = TaggedTemplateExpression; + exports.TemplateElement = TemplateElement; + exports.TemplateLiteral = TemplateLiteral; + + function TaggedTemplateExpression(node) { + this.print(node.tag, node); + this.print(node.typeParameters, node); + this.print(node.quasi, node); + } + + function TemplateElement(node, parent) { + const isFirst = parent.quasis[0] === node; + const isLast = parent.quasis[parent.quasis.length - 1] === node; + const value = (isFirst ? "`" : "}") + node.value.raw + (isLast ? "`" : "${"); + this.token(value); + } + + function TemplateLiteral(node) { + const quasis = node.quasis; + + for (let i = 0; i < quasis.length; i++) { + this.print(quasis[i], node); + + if (i + 1 < quasis.length) { + this.print(node.expressions[i], node); + } + } + } + }); + + unwrapExports(templateLiterals); + var templateLiterals_1 = templateLiterals.TaggedTemplateExpression; + var templateLiterals_2 = templateLiterals.TemplateElement; + var templateLiterals_3 = templateLiterals.TemplateLiteral; + + var expressions = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.UnaryExpression = UnaryExpression; + exports.DoExpression = DoExpression; + exports.ParenthesizedExpression = ParenthesizedExpression; + exports.UpdateExpression = UpdateExpression; + exports.ConditionalExpression = ConditionalExpression; + exports.NewExpression = NewExpression; + exports.SequenceExpression = SequenceExpression; + exports.ThisExpression = ThisExpression; + exports.Super = Super; + exports.Decorator = Decorator; + exports.OptionalMemberExpression = OptionalMemberExpression; + exports.OptionalCallExpression = OptionalCallExpression; + exports.CallExpression = CallExpression; + exports.Import = Import; + exports.EmptyStatement = EmptyStatement; + exports.ExpressionStatement = ExpressionStatement; + exports.AssignmentPattern = AssignmentPattern; + exports.LogicalExpression = exports.BinaryExpression = exports.AssignmentExpression = AssignmentExpression; + exports.BindExpression = BindExpression; + exports.MemberExpression = MemberExpression; + exports.MetaProperty = MetaProperty; + exports.PrivateName = PrivateName; + exports.V8IntrinsicIdentifier = V8IntrinsicIdentifier; + exports.AwaitExpression = exports.YieldExpression = void 0; + + var t = _interopRequireWildcard(lib$1); + + var n = _interopRequireWildcard(node$2); + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + function UnaryExpression(node) { + if (node.operator === "void" || node.operator === "delete" || node.operator === "typeof" || node.operator === "throw") { + this.word(node.operator); + this.space(); + } else { + this.token(node.operator); + } + + this.print(node.argument, node); + } + + function DoExpression(node) { + this.word("do"); + this.space(); + this.print(node.body, node); + } + + function ParenthesizedExpression(node) { + this.token("("); + this.print(node.expression, node); + this.token(")"); + } + + function UpdateExpression(node) { + if (node.prefix) { + this.token(node.operator); + this.print(node.argument, node); + } else { + this.startTerminatorless(true); + this.print(node.argument, node); + this.endTerminatorless(); + this.token(node.operator); + } + } + + function ConditionalExpression(node) { + this.print(node.test, node); + this.space(); + this.token("?"); + this.space(); + this.print(node.consequent, node); + this.space(); + this.token(":"); + this.space(); + this.print(node.alternate, node); + } + + function NewExpression(node, parent) { + this.word("new"); + this.space(); + this.print(node.callee, node); + + if (this.format.minified && node.arguments.length === 0 && !node.optional && !t.isCallExpression(parent, { + callee: node + }) && !t.isMemberExpression(parent) && !t.isNewExpression(parent)) { + return; + } + + this.print(node.typeArguments, node); + this.print(node.typeParameters, node); + + if (node.optional) { + this.token("?."); + } + + this.token("("); + this.printList(node.arguments, node); + this.token(")"); + } + + function SequenceExpression(node) { + this.printList(node.expressions, node); + } + + function ThisExpression() { + this.word("this"); + } + + function Super() { + this.word("super"); + } + + function Decorator(node) { + this.token("@"); + this.print(node.expression, node); + this.newline(); + } + + function OptionalMemberExpression(node) { + this.print(node.object, node); + + if (!node.computed && t.isMemberExpression(node.property)) { + throw new TypeError("Got a MemberExpression for MemberExpression property"); + } + + let computed = node.computed; + + if (t.isLiteral(node.property) && typeof node.property.value === "number") { + computed = true; + } + + if (node.optional) { + this.token("?."); + } + + if (computed) { + this.token("["); + this.print(node.property, node); + this.token("]"); + } else { + if (!node.optional) { + this.token("."); + } + + this.print(node.property, node); + } + } + + function OptionalCallExpression(node) { + this.print(node.callee, node); + this.print(node.typeArguments, node); + this.print(node.typeParameters, node); + + if (node.optional) { + this.token("?."); + } + + this.token("("); + this.printList(node.arguments, node); + this.token(")"); + } + + function CallExpression(node) { + this.print(node.callee, node); + this.print(node.typeArguments, node); + this.print(node.typeParameters, node); + this.token("("); + this.printList(node.arguments, node); + this.token(")"); + } + + function Import() { + this.word("import"); + } + + function buildYieldAwait(keyword) { + return function (node) { + this.word(keyword); + + if (node.delegate) { + this.token("*"); + } + + if (node.argument) { + this.space(); + const terminatorState = this.startTerminatorless(); + this.print(node.argument, node); + this.endTerminatorless(terminatorState); + } + }; + } + + const YieldExpression = buildYieldAwait("yield"); + exports.YieldExpression = YieldExpression; + const AwaitExpression = buildYieldAwait("await"); + exports.AwaitExpression = AwaitExpression; + + function EmptyStatement() { + this.semicolon(true); + } + + function ExpressionStatement(node) { + this.print(node.expression, node); + this.semicolon(); + } + + function AssignmentPattern(node) { + this.print(node.left, node); + if (node.left.optional) this.token("?"); + this.print(node.left.typeAnnotation, node); + this.space(); + this.token("="); + this.space(); + this.print(node.right, node); + } + + function AssignmentExpression(node, parent) { + const parens = this.inForStatementInitCounter && node.operator === "in" && !n.needsParens(node, parent); + + if (parens) { + this.token("("); + } + + this.print(node.left, node); + this.space(); + + if (node.operator === "in" || node.operator === "instanceof") { + this.word(node.operator); + } else { + this.token(node.operator); + } + + this.space(); + this.print(node.right, node); + + if (parens) { + this.token(")"); + } + } + + function BindExpression(node) { + this.print(node.object, node); + this.token("::"); + this.print(node.callee, node); + } + + function MemberExpression(node) { + this.print(node.object, node); + + if (!node.computed && t.isMemberExpression(node.property)) { + throw new TypeError("Got a MemberExpression for MemberExpression property"); + } + + let computed = node.computed; + + if (t.isLiteral(node.property) && typeof node.property.value === "number") { + computed = true; + } + + if (computed) { + this.token("["); + this.print(node.property, node); + this.token("]"); + } else { + this.token("."); + this.print(node.property, node); + } + } + + function MetaProperty(node) { + this.print(node.meta, node); + this.token("."); + this.print(node.property, node); + } + + function PrivateName(node) { + this.token("#"); + this.print(node.id, node); + } + + function V8IntrinsicIdentifier(node) { + this.token("%"); + this.word(node.name); + } + }); + + unwrapExports(expressions); + var expressions_1 = expressions.UnaryExpression; + var expressions_2 = expressions.DoExpression; + var expressions_3 = expressions.ParenthesizedExpression; + var expressions_4 = expressions.UpdateExpression; + var expressions_5 = expressions.ConditionalExpression; + var expressions_6 = expressions.NewExpression; + var expressions_7 = expressions.SequenceExpression; + var expressions_8 = expressions.ThisExpression; + var expressions_9 = expressions.Super; + var expressions_10 = expressions.Decorator; + var expressions_11 = expressions.OptionalMemberExpression; + var expressions_12 = expressions.OptionalCallExpression; + var expressions_13 = expressions.CallExpression; + var expressions_14 = expressions.Import; + var expressions_15 = expressions.EmptyStatement; + var expressions_16 = expressions.ExpressionStatement; + var expressions_17 = expressions.AssignmentPattern; + var expressions_18 = expressions.LogicalExpression; + var expressions_19 = expressions.BinaryExpression; + var expressions_20 = expressions.AssignmentExpression; + var expressions_21 = expressions.BindExpression; + var expressions_22 = expressions.MemberExpression; + var expressions_23 = expressions.MetaProperty; + var expressions_24 = expressions.PrivateName; + var expressions_25 = expressions.V8IntrinsicIdentifier; + var expressions_26 = expressions.AwaitExpression; + var expressions_27 = expressions.YieldExpression; + + var statements = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.WithStatement = WithStatement; + exports.IfStatement = IfStatement; + exports.ForStatement = ForStatement; + exports.WhileStatement = WhileStatement; + exports.DoWhileStatement = DoWhileStatement; + exports.LabeledStatement = LabeledStatement; + exports.TryStatement = TryStatement; + exports.CatchClause = CatchClause; + exports.SwitchStatement = SwitchStatement; + exports.SwitchCase = SwitchCase; + exports.DebuggerStatement = DebuggerStatement; + exports.VariableDeclaration = VariableDeclaration; + exports.VariableDeclarator = VariableDeclarator; + exports.ThrowStatement = exports.BreakStatement = exports.ReturnStatement = exports.ContinueStatement = exports.ForOfStatement = exports.ForInStatement = void 0; + + var t = _interopRequireWildcard(lib$1); + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + function WithStatement(node) { + this.word("with"); + this.space(); + this.token("("); + this.print(node.object, node); + this.token(")"); + this.printBlock(node); + } + + function IfStatement(node) { + this.word("if"); + this.space(); + this.token("("); + this.print(node.test, node); + this.token(")"); + this.space(); + const needsBlock = node.alternate && t.isIfStatement(getLastStatement(node.consequent)); + + if (needsBlock) { + this.token("{"); + this.newline(); + this.indent(); + } + + this.printAndIndentOnComments(node.consequent, node); + + if (needsBlock) { + this.dedent(); + this.newline(); + this.token("}"); + } + + if (node.alternate) { + if (this.endsWith("}")) this.space(); + this.word("else"); + this.space(); + this.printAndIndentOnComments(node.alternate, node); + } + } + + function getLastStatement(statement) { + if (!t.isStatement(statement.body)) return statement; + return getLastStatement(statement.body); + } + + function ForStatement(node) { + this.word("for"); + this.space(); + this.token("("); + this.inForStatementInitCounter++; + this.print(node.init, node); + this.inForStatementInitCounter--; + this.token(";"); + + if (node.test) { + this.space(); + this.print(node.test, node); + } + + this.token(";"); + + if (node.update) { + this.space(); + this.print(node.update, node); + } + + this.token(")"); + this.printBlock(node); + } + + function WhileStatement(node) { + this.word("while"); + this.space(); + this.token("("); + this.print(node.test, node); + this.token(")"); + this.printBlock(node); + } + + const buildForXStatement = function (op) { + return function (node) { + this.word("for"); + this.space(); + + if (op === "of" && node.await) { + this.word("await"); + this.space(); + } + + this.token("("); + this.print(node.left, node); + this.space(); + this.word(op); + this.space(); + this.print(node.right, node); + this.token(")"); + this.printBlock(node); + }; + }; + + const ForInStatement = buildForXStatement("in"); + exports.ForInStatement = ForInStatement; + const ForOfStatement = buildForXStatement("of"); + exports.ForOfStatement = ForOfStatement; + + function DoWhileStatement(node) { + this.word("do"); + this.space(); + this.print(node.body, node); + this.space(); + this.word("while"); + this.space(); + this.token("("); + this.print(node.test, node); + this.token(")"); + this.semicolon(); + } + + function buildLabelStatement(prefix, key = "label") { + return function (node) { + this.word(prefix); + const label = node[key]; + + if (label) { + this.space(); + const isLabel = key == "label"; + const terminatorState = this.startTerminatorless(isLabel); + this.print(label, node); + this.endTerminatorless(terminatorState); + } + + this.semicolon(); + }; + } + + const ContinueStatement = buildLabelStatement("continue"); + exports.ContinueStatement = ContinueStatement; + const ReturnStatement = buildLabelStatement("return", "argument"); + exports.ReturnStatement = ReturnStatement; + const BreakStatement = buildLabelStatement("break"); + exports.BreakStatement = BreakStatement; + const ThrowStatement = buildLabelStatement("throw", "argument"); + exports.ThrowStatement = ThrowStatement; + + function LabeledStatement(node) { + this.print(node.label, node); + this.token(":"); + this.space(); + this.print(node.body, node); + } + + function TryStatement(node) { + this.word("try"); + this.space(); + this.print(node.block, node); + this.space(); + + if (node.handlers) { + this.print(node.handlers[0], node); + } else { + this.print(node.handler, node); + } + + if (node.finalizer) { + this.space(); + this.word("finally"); + this.space(); + this.print(node.finalizer, node); + } + } + + function CatchClause(node) { + this.word("catch"); + this.space(); + + if (node.param) { + this.token("("); + this.print(node.param, node); + this.print(node.param.typeAnnotation, node); + this.token(")"); + this.space(); + } + + this.print(node.body, node); + } + + function SwitchStatement(node) { + this.word("switch"); + this.space(); + this.token("("); + this.print(node.discriminant, node); + this.token(")"); + this.space(); + this.token("{"); + this.printSequence(node.cases, node, { + indent: true, + + addNewlines(leading, cas) { + if (!leading && node.cases[node.cases.length - 1] === cas) return -1; + } + + }); + this.token("}"); + } + + function SwitchCase(node) { + if (node.test) { + this.word("case"); + this.space(); + this.print(node.test, node); + this.token(":"); + } else { + this.word("default"); + this.token(":"); + } + + if (node.consequent.length) { + this.newline(); + this.printSequence(node.consequent, node, { + indent: true + }); + } + } + + function DebuggerStatement() { + this.word("debugger"); + this.semicolon(); + } + + function variableDeclarationIndent() { + this.token(","); + this.newline(); + if (this.endsWith("\n")) for (let i = 0; i < 4; i++) this.space(true); + } + + function constDeclarationIndent() { + this.token(","); + this.newline(); + if (this.endsWith("\n")) for (let i = 0; i < 6; i++) this.space(true); + } + + function VariableDeclaration(node, parent) { + if (node.declare) { + this.word("declare"); + this.space(); + } + + this.word(node.kind); + this.space(); + let hasInits = false; + + if (!t.isFor(parent)) { + for (const declar of node.declarations) { + if (declar.init) { + hasInits = true; + } + } + } + + let separator; + + if (hasInits) { + separator = node.kind === "const" ? constDeclarationIndent : variableDeclarationIndent; + } + + this.printList(node.declarations, node, { + separator + }); + + if (t.isFor(parent)) { + if (parent.left === node || parent.init === node) return; + } + + this.semicolon(); + } + + function VariableDeclarator(node) { + this.print(node.id, node); + if (node.definite) this.token("!"); + this.print(node.id.typeAnnotation, node); + + if (node.init) { + this.space(); + this.token("="); + this.space(); + this.print(node.init, node); + } + } + }); + + unwrapExports(statements); + var statements_1 = statements.WithStatement; + var statements_2 = statements.IfStatement; + var statements_3 = statements.ForStatement; + var statements_4 = statements.WhileStatement; + var statements_5 = statements.DoWhileStatement; + var statements_6 = statements.LabeledStatement; + var statements_7 = statements.TryStatement; + var statements_8 = statements.CatchClause; + var statements_9 = statements.SwitchStatement; + var statements_10 = statements.SwitchCase; + var statements_11 = statements.DebuggerStatement; + var statements_12 = statements.VariableDeclaration; + var statements_13 = statements.VariableDeclarator; + var statements_14 = statements.ThrowStatement; + var statements_15 = statements.BreakStatement; + var statements_16 = statements.ReturnStatement; + var statements_17 = statements.ContinueStatement; + var statements_18 = statements.ForOfStatement; + var statements_19 = statements.ForInStatement; + + var classes = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.ClassExpression = exports.ClassDeclaration = ClassDeclaration; + exports.ClassBody = ClassBody; + exports.ClassProperty = ClassProperty; + exports.ClassPrivateProperty = ClassPrivateProperty; + exports.ClassMethod = ClassMethod; + exports.ClassPrivateMethod = ClassPrivateMethod; + exports._classMethodHead = _classMethodHead; + exports.StaticBlock = StaticBlock; + + var t = _interopRequireWildcard(lib$1); + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + function ClassDeclaration(node, parent) { + if (!this.format.decoratorsBeforeExport || !t.isExportDefaultDeclaration(parent) && !t.isExportNamedDeclaration(parent)) { + this.printJoin(node.decorators, node); + } + + if (node.declare) { + this.word("declare"); + this.space(); + } + + if (node.abstract) { + this.word("abstract"); + this.space(); + } + + this.word("class"); + + if (node.id) { + this.space(); + this.print(node.id, node); + } + + this.print(node.typeParameters, node); + + if (node.superClass) { + this.space(); + this.word("extends"); + this.space(); + this.print(node.superClass, node); + this.print(node.superTypeParameters, node); + } + + if (node.implements) { + this.space(); + this.word("implements"); + this.space(); + this.printList(node.implements, node); + } + + this.space(); + this.print(node.body, node); + } + + function ClassBody(node) { + this.token("{"); + this.printInnerComments(node); + + if (node.body.length === 0) { + this.token("}"); + } else { + this.newline(); + this.indent(); + this.printSequence(node.body, node); + this.dedent(); + if (!this.endsWith("\n")) this.newline(); + this.rightBrace(); + } + } + + function ClassProperty(node) { + this.printJoin(node.decorators, node); + this.tsPrintClassMemberModifiers(node, true); + + if (node.computed) { + this.token("["); + this.print(node.key, node); + this.token("]"); + } else { + this._variance(node); + + this.print(node.key, node); + } + + if (node.optional) { + this.token("?"); + } + + if (node.definite) { + this.token("!"); + } + + this.print(node.typeAnnotation, node); + + if (node.value) { + this.space(); + this.token("="); + this.space(); + this.print(node.value, node); + } + + this.semicolon(); + } + + function ClassPrivateProperty(node) { + this.printJoin(node.decorators, node); + + if (node.static) { + this.word("static"); + this.space(); + } + + this.print(node.key, node); + this.print(node.typeAnnotation, node); + + if (node.value) { + this.space(); + this.token("="); + this.space(); + this.print(node.value, node); + } + + this.semicolon(); + } + + function ClassMethod(node) { + this._classMethodHead(node); + + this.space(); + this.print(node.body, node); + } + + function ClassPrivateMethod(node) { + this._classMethodHead(node); + + this.space(); + this.print(node.body, node); + } + + function _classMethodHead(node) { + this.printJoin(node.decorators, node); + this.tsPrintClassMemberModifiers(node, false); + + this._methodHead(node); + } + + function StaticBlock(node) { + this.word("static"); + this.space(); + this.token("{"); + + if (node.body.length === 0) { + this.token("}"); + } else { + this.newline(); + this.printSequence(node.body, node, { + indent: true + }); + this.rightBrace(); + } + } + }); + + unwrapExports(classes); + var classes_1 = classes.ClassExpression; + var classes_2 = classes.ClassDeclaration; + var classes_3 = classes.ClassBody; + var classes_4 = classes.ClassProperty; + var classes_5 = classes.ClassPrivateProperty; + var classes_6 = classes.ClassMethod; + var classes_7 = classes.ClassPrivateMethod; + var classes_8 = classes._classMethodHead; + var classes_9 = classes.StaticBlock; + + var methods = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports._params = _params; + exports._parameters = _parameters; + exports._param = _param; + exports._methodHead = _methodHead; + exports._predicate = _predicate; + exports._functionHead = _functionHead; + exports.FunctionDeclaration = exports.FunctionExpression = FunctionExpression; + exports.ArrowFunctionExpression = ArrowFunctionExpression; + + var t = _interopRequireWildcard(lib$1); + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + function _params(node) { + this.print(node.typeParameters, node); + this.token("("); + + this._parameters(node.params, node); + + this.token(")"); + this.print(node.returnType, node); + } + + function _parameters(parameters, parent) { + for (let i = 0; i < parameters.length; i++) { + this._param(parameters[i], parent); + + if (i < parameters.length - 1) { + this.token(","); + this.space(); + } + } + } + + function _param(parameter, parent) { + this.printJoin(parameter.decorators, parameter); + this.print(parameter, parent); + if (parameter.optional) this.token("?"); + this.print(parameter.typeAnnotation, parameter); + } + + function _methodHead(node) { + const kind = node.kind; + const key = node.key; + + if (kind === "get" || kind === "set") { + this.word(kind); + this.space(); + } + + if (node.async) { + this._catchUp("start", key.loc); + + this.word("async"); + this.space(); + } + + if (kind === "method" || kind === "init") { + if (node.generator) { + this.token("*"); + } + } + + if (node.computed) { + this.token("["); + this.print(key, node); + this.token("]"); + } else { + this.print(key, node); + } + + if (node.optional) { + this.token("?"); + } + + this._params(node); + } + + function _predicate(node) { + if (node.predicate) { + if (!node.returnType) { + this.token(":"); + } + + this.space(); + this.print(node.predicate, node); + } + } + + function _functionHead(node) { + if (node.async) { + this.word("async"); + this.space(); + } + + this.word("function"); + if (node.generator) this.token("*"); + this.space(); + + if (node.id) { + this.print(node.id, node); + } + + this._params(node); + + this._predicate(node); + } + + function FunctionExpression(node) { + this._functionHead(node); + + this.space(); + this.print(node.body, node); + } + + function ArrowFunctionExpression(node) { + if (node.async) { + this.word("async"); + this.space(); + } + + const firstParam = node.params[0]; + + if (node.params.length === 1 && t.isIdentifier(firstParam) && !hasTypes(node, firstParam)) { + if ((this.format.retainLines || node.async) && node.loc && node.body.loc && node.loc.start.line < node.body.loc.start.line) { + this.token("("); + + if (firstParam.loc && firstParam.loc.start.line > node.loc.start.line) { + this.indent(); + this.print(firstParam, node); + this.dedent(); + + this._catchUp("start", node.body.loc); + } else { + this.print(firstParam, node); + } + + this.token(")"); + } else { + this.print(firstParam, node); + } + } else { + this._params(node); + } + + this._predicate(node); + + this.space(); + this.token("=>"); + this.space(); + this.print(node.body, node); + } + + function hasTypes(node, param) { + return node.typeParameters || node.returnType || param.typeAnnotation || param.optional || param.trailingComments; + } + }); + + unwrapExports(methods); + var methods_1 = methods._params; + var methods_2 = methods._parameters; + var methods_3 = methods._param; + var methods_4 = methods._methodHead; + var methods_5 = methods._predicate; + var methods_6 = methods._functionHead; + var methods_7 = methods.FunctionDeclaration; + var methods_8 = methods.FunctionExpression; + var methods_9 = methods.ArrowFunctionExpression; + + var modules = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.ImportSpecifier = ImportSpecifier; + exports.ImportDefaultSpecifier = ImportDefaultSpecifier; + exports.ExportDefaultSpecifier = ExportDefaultSpecifier; + exports.ExportSpecifier = ExportSpecifier; + exports.ExportNamespaceSpecifier = ExportNamespaceSpecifier; + exports.ExportAllDeclaration = ExportAllDeclaration; + exports.ExportNamedDeclaration = ExportNamedDeclaration; + exports.ExportDefaultDeclaration = ExportDefaultDeclaration; + exports.ImportDeclaration = ImportDeclaration; + exports.ImportAttribute = ImportAttribute; + exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; + + var t = _interopRequireWildcard(lib$1); + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + function ImportSpecifier(node) { + if (node.importKind === "type" || node.importKind === "typeof") { + this.word(node.importKind); + this.space(); + } + + this.print(node.imported, node); + + if (node.local && node.local.name !== node.imported.name) { + this.space(); + this.word("as"); + this.space(); + this.print(node.local, node); + } + } + + function ImportDefaultSpecifier(node) { + this.print(node.local, node); + } + + function ExportDefaultSpecifier(node) { + this.print(node.exported, node); + } + + function ExportSpecifier(node) { + this.print(node.local, node); + + if (node.exported && node.local.name !== node.exported.name) { + this.space(); + this.word("as"); + this.space(); + this.print(node.exported, node); + } + } + + function ExportNamespaceSpecifier(node) { + this.token("*"); + this.space(); + this.word("as"); + this.space(); + this.print(node.exported, node); + } + + function ExportAllDeclaration(node) { + this.word("export"); + this.space(); + + if (node.exportKind === "type") { + this.word("type"); + this.space(); + } + + this.token("*"); + this.space(); + this.word("from"); + this.space(); + this.print(node.source, node); + this.printAssertions(node); + this.semicolon(); + } + + function ExportNamedDeclaration(node) { + if (this.format.decoratorsBeforeExport && t.isClassDeclaration(node.declaration)) { + this.printJoin(node.declaration.decorators, node); + } + + this.word("export"); + this.space(); + ExportDeclaration.apply(this, arguments); + } + + function ExportDefaultDeclaration(node) { + if (this.format.decoratorsBeforeExport && t.isClassDeclaration(node.declaration)) { + this.printJoin(node.declaration.decorators, node); + } + + this.word("export"); + this.space(); + this.word("default"); + this.space(); + ExportDeclaration.apply(this, arguments); + } + + function ExportDeclaration(node) { + if (node.declaration) { + const declar = node.declaration; + this.print(declar, node); + if (!t.isStatement(declar)) this.semicolon(); + } else { + if (node.exportKind === "type") { + this.word("type"); + this.space(); + } + + const specifiers = node.specifiers.slice(0); + let hasSpecial = false; + + for (;;) { + const first = specifiers[0]; + + if (t.isExportDefaultSpecifier(first) || t.isExportNamespaceSpecifier(first)) { + hasSpecial = true; + this.print(specifiers.shift(), node); + + if (specifiers.length) { + this.token(","); + this.space(); + } + } else { + break; + } + } + + if (specifiers.length || !specifiers.length && !hasSpecial) { + this.token("{"); + + if (specifiers.length) { + this.space(); + this.printList(specifiers, node); + this.space(); + } + + this.token("}"); + } + + if (node.source) { + this.space(); + this.word("from"); + this.space(); + this.print(node.source, node); + this.printAssertions(node); + } + + this.semicolon(); + } + } + + function ImportDeclaration(node) { + var _node$attributes; + + this.word("import"); + this.space(); + + if (node.importKind === "type" || node.importKind === "typeof") { + this.word(node.importKind); + this.space(); + } + + const specifiers = node.specifiers.slice(0); + + if (specifiers == null ? void 0 : specifiers.length) { + for (;;) { + const first = specifiers[0]; + + if (t.isImportDefaultSpecifier(first) || t.isImportNamespaceSpecifier(first)) { + this.print(specifiers.shift(), node); + + if (specifiers.length) { + this.token(","); + this.space(); + } + } else { + break; + } + } + + if (specifiers.length) { + this.token("{"); + this.space(); + this.printList(specifiers, node); + this.space(); + this.token("}"); + } + + this.space(); + this.word("from"); + this.space(); + } + + this.print(node.source, node); + this.printAssertions(node); + + if ((_node$attributes = node.attributes) == null ? void 0 : _node$attributes.length) { + this.space(); + this.word("with"); + this.space(); + this.printList(node.attributes, node); + } + + this.semicolon(); + } + + function ImportAttribute(node) { + this.print(node.key); + this.token(":"); + this.space(); + this.print(node.value); + } + + function ImportNamespaceSpecifier(node) { + this.token("*"); + this.space(); + this.word("as"); + this.space(); + this.print(node.local, node); + } + }); + + unwrapExports(modules); + var modules_1 = modules.ImportSpecifier; + var modules_2 = modules.ImportDefaultSpecifier; + var modules_3 = modules.ExportDefaultSpecifier; + var modules_4 = modules.ExportSpecifier; + var modules_5 = modules.ExportNamespaceSpecifier; + var modules_6 = modules.ExportAllDeclaration; + var modules_7 = modules.ExportNamedDeclaration; + var modules_8 = modules.ExportDefaultDeclaration; + var modules_9 = modules.ImportDeclaration; + var modules_10 = modules.ImportAttribute; + var modules_11 = modules.ImportNamespaceSpecifier; + + const object = {}; + const hasOwnProperty$c = object.hasOwnProperty; + const forOwn = (object, callback) => { + for (const key in object) { + if (hasOwnProperty$c.call(object, key)) { + callback(key, object[key]); + } + } + }; + + const extend = (destination, source) => { + if (!source) { + return destination; + } + forOwn(source, (key, value) => { + destination[key] = value; + }); + return destination; + }; + + const forEach = (array, callback) => { + const length = array.length; + let index = -1; + while (++index < length) { + callback(array[index]); + } + }; + + const toString$1 = object.toString; + const isArray$3 = Array.isArray; + const isBuffer$2 = isBuffer; + const isObject$2 = (value) => { + // This is a very simple check, but it’s good enough for what we need. + return toString$1.call(value) == '[object Object]'; + }; + const isString$1 = (value) => { + return typeof value == 'string' || + toString$1.call(value) == '[object String]'; + }; + const isNumber$1 = (value) => { + return typeof value == 'number' || + toString$1.call(value) == '[object Number]'; + }; + const isFunction$2 = (value) => { + return typeof value == 'function'; + }; + const isMap$1 = (value) => { + return toString$1.call(value) == '[object Map]'; + }; + const isSet$1 = (value) => { + return toString$1.call(value) == '[object Set]'; + }; + + /*--------------------------------------------------------------------------*/ + + // https://mathiasbynens.be/notes/javascript-escapes#single + const singleEscapes = { + '"': '\\"', + '\'': '\\\'', + '\\': '\\\\', + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t' + // `\v` is omitted intentionally, because in IE < 9, '\v' == 'v'. + // '\v': '\\x0B' + }; + const regexSingleEscape = /["'\\\b\f\n\r\t]/; + + const regexDigit = /[0-9]/; + const regexWhitelist = /[ !#-&\(-\[\]-_a-~]/; + + const jsesc = (argument, options) => { + const increaseIndentation = () => { + oldIndent = indent; + ++options.indentLevel; + indent = options.indent.repeat(options.indentLevel); + }; + // Handle options + const defaults = { + 'escapeEverything': false, + 'minimal': false, + 'isScriptContext': false, + 'quotes': 'single', + 'wrap': false, + 'es6': false, + 'json': false, + 'compact': true, + 'lowercaseHex': false, + 'numbers': 'decimal', + 'indent': '\t', + 'indentLevel': 0, + '__inline1__': false, + '__inline2__': false + }; + const json = options && options.json; + if (json) { + defaults.quotes = 'double'; + defaults.wrap = true; + } + options = extend(defaults, options); + if ( + options.quotes != 'single' && + options.quotes != 'double' && + options.quotes != 'backtick' + ) { + options.quotes = 'single'; + } + const quote = options.quotes == 'double' ? + '"' : + (options.quotes == 'backtick' ? + '`' : + '\'' + ); + const compact = options.compact; + const lowercaseHex = options.lowercaseHex; + let indent = options.indent.repeat(options.indentLevel); + let oldIndent = ''; + const inline1 = options.__inline1__; + const inline2 = options.__inline2__; + const newLine = compact ? '' : '\n'; + let result; + let isEmpty = true; + const useBinNumbers = options.numbers == 'binary'; + const useOctNumbers = options.numbers == 'octal'; + const useDecNumbers = options.numbers == 'decimal'; + const useHexNumbers = options.numbers == 'hexadecimal'; + + if (json && argument && isFunction$2(argument.toJSON)) { + argument = argument.toJSON(); + } + + if (!isString$1(argument)) { + if (isMap$1(argument)) { + if (argument.size == 0) { + return 'new Map()'; + } + if (!compact) { + options.__inline1__ = true; + options.__inline2__ = false; + } + return 'new Map(' + jsesc(Array.from(argument), options) + ')'; + } + if (isSet$1(argument)) { + if (argument.size == 0) { + return 'new Set()'; + } + return 'new Set(' + jsesc(Array.from(argument), options) + ')'; + } + if (isBuffer$2(argument)) { + if (argument.length == 0) { + return 'Buffer.from([])'; + } + return 'Buffer.from(' + jsesc(Array.from(argument), options) + ')'; + } + if (isArray$3(argument)) { + result = []; + options.wrap = true; + if (inline1) { + options.__inline1__ = false; + options.__inline2__ = true; + } + if (!inline2) { + increaseIndentation(); + } + forEach(argument, (value) => { + isEmpty = false; + if (inline2) { + options.__inline2__ = false; + } + result.push( + (compact || inline2 ? '' : indent) + + jsesc(value, options) + ); + }); + if (isEmpty) { + return '[]'; + } + if (inline2) { + return '[' + result.join(', ') + ']'; + } + return '[' + newLine + result.join(',' + newLine) + newLine + + (compact ? '' : oldIndent) + ']'; + } else if (isNumber$1(argument)) { + if (json) { + // Some number values (e.g. `Infinity`) cannot be represented in JSON. + return JSON.stringify(argument); + } + if (useDecNumbers) { + return String(argument); + } + if (useHexNumbers) { + let hexadecimal = argument.toString(16); + if (!lowercaseHex) { + hexadecimal = hexadecimal.toUpperCase(); + } + return '0x' + hexadecimal; + } + if (useBinNumbers) { + return '0b' + argument.toString(2); + } + if (useOctNumbers) { + return '0o' + argument.toString(8); + } + } else if (!isObject$2(argument)) { + if (json) { + // For some values (e.g. `undefined`, `function` objects), + // `JSON.stringify(value)` returns `undefined` (which isn’t valid + // JSON) instead of `'null'`. + return JSON.stringify(argument) || 'null'; + } + return String(argument); + } else { // it’s an object + result = []; + options.wrap = true; + increaseIndentation(); + forOwn(argument, (key, value) => { + isEmpty = false; + result.push( + (compact ? '' : indent) + + jsesc(key, options) + ':' + + (compact ? '' : ' ') + + jsesc(value, options) + ); + }); + if (isEmpty) { + return '{}'; + } + return '{' + newLine + result.join(',' + newLine) + newLine + + (compact ? '' : oldIndent) + '}'; + } + } + + const string = argument; + // Loop over each code unit in the string and escape it + let index = -1; + const length = string.length; + result = ''; + while (++index < length) { + const character = string.charAt(index); + if (options.es6) { + const first = string.charCodeAt(index); + if ( // check if it’s the start of a surrogate pair + first >= 0xD800 && first <= 0xDBFF && // high surrogate + length > index + 1 // there is a next code unit + ) { + const second = string.charCodeAt(index + 1); + if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + const codePoint = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + let hexadecimal = codePoint.toString(16); + if (!lowercaseHex) { + hexadecimal = hexadecimal.toUpperCase(); + } + result += '\\u{' + hexadecimal + '}'; + ++index; + continue; + } + } + } + if (!options.escapeEverything) { + if (regexWhitelist.test(character)) { + // It’s a printable ASCII character that is not `"`, `'` or `\`, + // so don’t escape it. + result += character; + continue; + } + if (character == '"') { + result += quote == character ? '\\"' : character; + continue; + } + if (character == '`') { + result += quote == character ? '\\`' : character; + continue; + } + if (character == '\'') { + result += quote == character ? '\\\'' : character; + continue; + } + } + if ( + character == '\0' && + !json && + !regexDigit.test(string.charAt(index + 1)) + ) { + result += '\\0'; + continue; + } + if (regexSingleEscape.test(character)) { + // no need for a `hasOwnProperty` check here + result += singleEscapes[character]; + continue; + } + const charCode = character.charCodeAt(0); + if (options.minimal && charCode != 0x2028 && charCode != 0x2029) { + result += character; + continue; + } + let hexadecimal = charCode.toString(16); + if (!lowercaseHex) { + hexadecimal = hexadecimal.toUpperCase(); + } + const longhand = hexadecimal.length > 2 || json; + const escaped = '\\' + (longhand ? 'u' : 'x') + + ('0000' + hexadecimal).slice(longhand ? -4 : -2); + result += escaped; + continue; + } + if (options.wrap) { + result = quote + result + quote; + } + if (quote == '`') { + result = result.replace(/\$\{/g, '\\\$\{'); + } + if (options.isScriptContext) { + // https://mathiasbynens.be/notes/etago + return result + .replace(/<\/(script|style)/gi, '<\\/$1') + .replace(/ * (any, kinda silly) + // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 + // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 + // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 + // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 + // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 + function replaceTildes (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceTilde(comp, options) + }).join(' ') + } + + function replaceTilde (comp, options) { + var r = options.loose ? re[TILDELOOSE] : re[TILDE]; + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } else if (pr) { + debug('replaceTilde pr', pr); + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else { + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + } + + debug('tilde return', ret); + return ret + }) + } + + // ^ --> * (any, kinda silly) + // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 + // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 + // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 + // ^1.2.3 --> >=1.2.3 <2.0.0 + // ^1.2.0 --> >=1.2.0 <2.0.0 + function replaceCarets (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceCaret(comp, options) + }).join(' ') + } + + function replaceCaret (comp, options) { + debug('caret', comp, options); + var r = options.loose ? re[CARETLOOSE] : re[CARET]; + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (isX(p)) { + if (M === '0') { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } else { + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; + } + } else if (pr) { + debug('replaceCaret pr', pr); + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + m + '.' + (+p + 1); + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + (+M + 1) + '.0.0'; + } + } else { + debug('no pr'); + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1); + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + } + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0'; + } + } + + debug('caret return', ret); + return ret + }) + } + + function replaceXRanges (comp, options) { + debug('replaceXRanges', comp, options); + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, options) + }).join(' ') + } + + function replaceXRange (comp, options) { + comp = comp.trim(); + var r = options.loose ? re[XRANGELOOSE] : re[XRANGE]; + return comp.replace(r, function (ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr); + var xM = isX(M); + var xm = xM || isX(m); + var xp = xm || isX(p); + var anyX = xp; + + if (gtlt === '=' && anyX) { + gtlt = ''; + } + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0; + } + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } + } + + ret = gtlt + M + '.' + m + '.' + p; + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } + + debug('xRange return', ret); + + return ret + }) + } + + // Because * is AND-ed with everything else in the comparator, + // and '' means "any version", just remove the *s entirely. + function replaceStars (comp, options) { + debug('replaceStars', comp, options); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], '') + } + + // This function is passed to string.replace(re[HYPHENRANGE]) + // M, m, patch, prerelease, build + // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 + // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do + // 1.2 - 3.4 => >=1.2.0 <3.5.0 + function hyphenReplace ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = ''; + } else if (isX(fm)) { + from = '>=' + fM + '.0.0'; + } else if (isX(fp)) { + from = '>=' + fM + '.' + fm + '.0'; + } else { + from = '>=' + from; + } + + if (isX(tM)) { + to = ''; + } else if (isX(tm)) { + to = '<' + (+tM + 1) + '.0.0'; + } else if (isX(tp)) { + to = '<' + tM + '.' + (+tm + 1) + '.0'; + } else if (tpr) { + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; + } else { + to = '<=' + to; + } + + return (from + ' ' + to).trim() + } + + // if ANY of the sets match ALL of its comparators, then pass + Range.prototype.test = function (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + version = new SemVer(version, this.options); + } + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + }; + + function testSet (set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (i = 0; i < set.length; i++) { + debug(set[i].semver); + if (set[i].semver === ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true + } + + exports.satisfies = satisfies; + function satisfies (version, range, options) { + try { + range = new Range(range, options); + } catch (er) { + return false + } + return range.test(version) + } + + exports.maxSatisfying = maxSatisfying; + function maxSatisfying (versions, range, options) { + var max = null; + var maxSV = null; + try { + var rangeObj = new Range(range, options); + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v; + maxSV = new SemVer(max, options); + } + } + }); + return max + } + + exports.minSatisfying = minSatisfying; + function minSatisfying (versions, range, options) { + var min = null; + var minSV = null; + try { + var rangeObj = new Range(range, options); + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v; + minSV = new SemVer(min, options); + } + } + }); + return min + } + + exports.minVersion = minVersion; + function minVersion (range, loose) { + range = new Range(range, loose); + + var minver = new SemVer('0.0.0'); + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0'); + if (range.test(minver)) { + return minver + } + + minver = null; + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i]; + + comparators.forEach(function (comparator) { + // Clone to avoid manipulating the comparator's semver object. + var compver = new SemVer(comparator.semver.version); + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + compver.raw = compver.format(); + /* fallthrough */ + case '': + case '>=': + if (!minver || gt(minver, compver)) { + minver = compver; + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error('Unexpected operation: ' + comparator.operator) + } + }); + } + + if (minver && range.test(minver)) { + return minver + } + + return null + } + + exports.validRange = validRange; + function validRange (range, options) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } + } + + // Determine if version is less than all the versions possible in the range + exports.ltr = ltr; + function ltr (version, range, options) { + return outside(version, range, '<', options) + } + + // Determine if version is greater than all the versions possible in the range. + exports.gtr = gtr; + function gtr (version, range, options) { + return outside(version, range, '>', options) + } + + exports.outside = outside; + function outside (version, range, hilo, options) { + version = new SemVer(version, options); + range = new Range(range, options); + + var gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i]; + + var high = null; + var low = null; + + comparators.forEach(function (comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0'); + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true + } + + exports.prerelease = prerelease; + function prerelease (version, options) { + var parsed = parse(version, options); + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null + } + + exports.intersects = intersects; + function intersects (r1, r2, options) { + r1 = new Range(r1, options); + r2 = new Range(r2, options); + return r1.intersects(r2) + } + + exports.coerce = coerce; + function coerce (version) { + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + var match = version.match(re[COERCE]); + + if (match == null) { + return null + } + + return parse(match[1] + + '.' + (match[2] || '0') + + '.' + (match[3] || '0')) + } + }); + var semver_1 = semver.SEMVER_SPEC_VERSION; + var semver_2 = semver.re; + var semver_3 = semver.src; + var semver_4 = semver.parse; + var semver_5 = semver.valid; + var semver_6 = semver.clean; + var semver_7 = semver.SemVer; + var semver_8 = semver.inc; + var semver_9 = semver.diff; + var semver_10 = semver.compareIdentifiers; + var semver_11 = semver.rcompareIdentifiers; + var semver_12 = semver.major; + var semver_13 = semver.minor; + var semver_14 = semver.patch; + var semver_15 = semver.compare; + var semver_16 = semver.compareLoose; + var semver_17 = semver.rcompare; + var semver_18 = semver.sort; + var semver_19 = semver.rsort; + var semver_20 = semver.gt; + var semver_21 = semver.lt; + var semver_22 = semver.eq; + var semver_23 = semver.neq; + var semver_24 = semver.gte; + var semver_25 = semver.lte; + var semver_26 = semver.cmp; + var semver_27 = semver.Comparator; + var semver_28 = semver.Range; + var semver_29 = semver.toComparators; + var semver_30 = semver.satisfies; + var semver_31 = semver.maxSatisfying; + var semver_32 = semver.minSatisfying; + var semver_33 = semver.minVersion; + var semver_34 = semver.validRange; + var semver_35 = semver.ltr; + var semver_36 = semver.gtr; + var semver_37 = semver.outside; + var semver_38 = semver.prerelease; + var semver_39 = semver.intersects; + var semver_40 = semver.coerce; + + var file = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = void 0; + + function helpers() { + const data = _interopRequireWildcard(lib$b); + + helpers = function () { + return data; + }; + + return data; + } + + function _traverse() { + const data = _interopRequireWildcard(lib$a); + + _traverse = function () { + return data; + }; + + return data; + } + + function _codeFrame() { + const data = lib$5; + + _codeFrame = function () { + return data; + }; + + return data; + } + + function t() { + const data = _interopRequireWildcard(lib$1); + + t = function () { + return data; + }; + + return data; + } + + function _helperModuleTransforms() { + const data = lib$h; + + _helperModuleTransforms = function () { + return data; + }; + + return data; + } + + function _semver() { + const data = _interopRequireDefault(semver); + + _semver = function () { + return data; + }; + + return data; + } + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + const errorVisitor = { + enter(path, state) { + const loc = path.node.loc; + + if (loc) { + state.loc = loc; + path.stop(); + } + } + + }; + + class File { + constructor(options, { + code, + ast, + inputMap + }) { + this._map = new Map(); + this.opts = void 0; + this.declarations = {}; + this.path = null; + this.ast = {}; + this.scope = void 0; + this.metadata = {}; + this.code = ""; + this.inputMap = null; + this.hub = { + file: this, + getCode: () => this.code, + getScope: () => this.scope, + addHelper: this.addHelper.bind(this), + buildError: this.buildCodeFrameError.bind(this) + }; + this.opts = options; + this.code = code; + this.ast = ast; + this.inputMap = inputMap; + this.path = _traverse().NodePath.get({ + hub: this.hub, + parentPath: null, + parent: this.ast, + container: this.ast, + key: "program" + }).setContext(); + this.scope = this.path.scope; + } + + get shebang() { + const { + interpreter + } = this.path.node; + return interpreter ? interpreter.value : ""; + } + + set shebang(value) { + if (value) { + this.path.get("interpreter").replaceWith(t().interpreterDirective(value)); + } else { + this.path.get("interpreter").remove(); + } + } + + set(key, val) { + if (key === "helpersNamespace") { + throw new Error("Babel 7.0.0-beta.56 has dropped support for the 'helpersNamespace' utility." + "If you are using @babel/plugin-external-helpers you will need to use a newer " + "version than the one you currently have installed. " + "If you have your own implementation, you'll want to explore using 'helperGenerator' " + "alongside 'file.availableHelper()'."); + } + + this._map.set(key, val); + } + + get(key) { + return this._map.get(key); + } + + has(key) { + return this._map.has(key); + } + + getModuleName() { + return (0, _helperModuleTransforms().getModuleName)(this.opts, this.opts); + } + + addImport() { + throw new Error("This API has been removed. If you're looking for this " + "functionality in Babel 7, you should import the " + "'@babel/helper-module-imports' module and use the functions exposed " + " from that module, such as 'addNamed' or 'addDefault'."); + } + + availableHelper(name, versionRange) { + let minVersion; + + try { + minVersion = helpers().minVersion(name); + } catch (err) { + if (err.code !== "BABEL_HELPER_UNKNOWN") throw err; + return false; + } + + if (typeof versionRange !== "string") return true; + if (_semver().default.valid(versionRange)) versionRange = `^${versionRange}`; + return !_semver().default.intersects(`<${minVersion}`, versionRange) && !_semver().default.intersects(`>=8.0.0`, versionRange); + } + + addHelper(name) { + const declar = this.declarations[name]; + if (declar) return t().cloneNode(declar); + const generator = this.get("helperGenerator"); + + if (generator) { + const res = generator(name); + if (res) return res; + } + + helpers().ensure(name, File); + const uid = this.declarations[name] = this.scope.generateUidIdentifier(name); + const dependencies = {}; + + for (const dep of helpers().getDependencies(name)) { + dependencies[dep] = this.addHelper(dep); + } + + const { + nodes, + globals + } = helpers().get(name, dep => dependencies[dep], uid, Object.keys(this.scope.getAllBindings())); + globals.forEach(name => { + if (this.path.scope.hasBinding(name, true)) { + this.path.scope.rename(name); + } + }); + nodes.forEach(node => { + node._compact = true; + }); + this.path.unshiftContainer("body", nodes); + this.path.get("body").forEach(path => { + if (nodes.indexOf(path.node) === -1) return; + if (path.isVariableDeclaration()) this.scope.registerDeclaration(path); + }); + return uid; + } + + addTemplateObject() { + throw new Error("This function has been moved into the template literal transform itself."); + } + + buildCodeFrameError(node, msg, Error = SyntaxError) { + let loc = node && (node.loc || node._loc); + + if (!loc && node) { + const state = { + loc: null + }; + (0, _traverse().default)(node, errorVisitor, this.scope, state); + loc = state.loc; + let txt = "This is an error on an internal node. Probably an internal error."; + if (loc) txt += " Location has been estimated."; + msg += ` (${txt})`; + } + + if (loc) { + const { + highlightCode = true + } = this.opts; + msg += "\n" + (0, _codeFrame().codeFrameColumns)(this.code, { + start: { + line: loc.start.line, + column: loc.start.column + 1 + }, + end: loc.end && loc.start.line === loc.end.line ? { + line: loc.end.line, + column: loc.end.column + 1 + } : undefined + }, { + highlightCode + }); + } + + return new Error(msg); + } + + } + + exports.default = File; + }); + + unwrapExports(file); + + var buildExternalHelpers = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = _default; + + function helpers() { + const data = _interopRequireWildcard(lib$b); + + helpers = function () { + return data; + }; + + return data; + } + + function _generator() { + const data = _interopRequireDefault(lib$3); + + _generator = function () { + return data; + }; + + return data; + } + + function _template() { + const data = _interopRequireDefault(lib$8); + + _template = function () { + return data; + }; + + return data; + } + + function t() { + const data = _interopRequireWildcard(lib$1); + + t = function () { + return data; + }; + + return data; + } + + var _file = _interopRequireDefault(file); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + const buildUmdWrapper = replacements => (_template().default)` + (function (root, factory) { + if (typeof define === "function" && define.amd) { + define(AMD_ARGUMENTS, factory); + } else if (typeof exports === "object") { + factory(COMMON_ARGUMENTS); + } else { + factory(BROWSER_ARGUMENTS); + } + })(UMD_ROOT, function (FACTORY_PARAMETERS) { + FACTORY_BODY + }); + `(replacements); + + function buildGlobal(allowlist) { + const namespace = t().identifier("babelHelpers"); + const body = []; + const container = t().functionExpression(null, [t().identifier("global")], t().blockStatement(body)); + const tree = t().program([t().expressionStatement(t().callExpression(container, [t().conditionalExpression(t().binaryExpression("===", t().unaryExpression("typeof", t().identifier("global")), t().stringLiteral("undefined")), t().identifier("self"), t().identifier("global"))]))]); + body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().assignmentExpression("=", t().memberExpression(t().identifier("global"), namespace), t().objectExpression([])))])); + buildHelpers(body, namespace, allowlist); + return tree; + } + + function buildModule(allowlist) { + const body = []; + const refs = buildHelpers(body, null, allowlist); + body.unshift(t().exportNamedDeclaration(null, Object.keys(refs).map(name => { + return t().exportSpecifier(t().cloneNode(refs[name]), t().identifier(name)); + }))); + return t().program(body, [], "module"); + } + + function buildUmd(allowlist) { + const namespace = t().identifier("babelHelpers"); + const body = []; + body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().identifier("global"))])); + buildHelpers(body, namespace, allowlist); + return t().program([buildUmdWrapper({ + FACTORY_PARAMETERS: t().identifier("global"), + BROWSER_ARGUMENTS: t().assignmentExpression("=", t().memberExpression(t().identifier("root"), namespace), t().objectExpression([])), + COMMON_ARGUMENTS: t().identifier("exports"), + AMD_ARGUMENTS: t().arrayExpression([t().stringLiteral("exports")]), + FACTORY_BODY: body, + UMD_ROOT: t().identifier("this") + })]); + } + + function buildVar(allowlist) { + const namespace = t().identifier("babelHelpers"); + const body = []; + body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().objectExpression([]))])); + const tree = t().program(body); + buildHelpers(body, namespace, allowlist); + body.push(t().expressionStatement(namespace)); + return tree; + } + + function buildHelpers(body, namespace, allowlist) { + const getHelperReference = name => { + return namespace ? t().memberExpression(namespace, t().identifier(name)) : t().identifier(`_${name}`); + }; + + const refs = {}; + helpers().list.forEach(function (name) { + if (allowlist && allowlist.indexOf(name) < 0) return; + const ref = refs[name] = getHelperReference(name); + helpers().ensure(name, _file.default); + const { + nodes + } = helpers().get(name, getHelperReference, ref); + body.push(...nodes); + }); + return refs; + } + + function _default(allowlist, outputType = "global") { + let tree; + const build = { + global: buildGlobal, + module: buildModule, + umd: buildUmd, + var: buildVar + }[outputType]; + + if (build) { + tree = build(allowlist); + } else { + throw new Error(`Unsupported output type ${outputType}`); + } + + return (0, _generator().default)(tree).code; + } + }); + + unwrapExports(buildExternalHelpers); + + // These use the global symbol registry so that multiple copies of this + // library can work together in case they are not deduped. + const GENSYNC_START = Symbol.for("gensync:v1:start"); + const GENSYNC_SUSPEND = Symbol.for("gensync:v1:suspend"); + + const GENSYNC_EXPECTED_START = "GENSYNC_EXPECTED_START"; + const GENSYNC_EXPECTED_SUSPEND = "GENSYNC_EXPECTED_SUSPEND"; + const GENSYNC_OPTIONS_ERROR = "GENSYNC_OPTIONS_ERROR"; + const GENSYNC_RACE_NONEMPTY = "GENSYNC_RACE_NONEMPTY"; + const GENSYNC_ERRBACK_NO_CALLBACK = "GENSYNC_ERRBACK_NO_CALLBACK"; + + var gensync = Object.assign( + function gensync(optsOrFn) { + let genFn = optsOrFn; + if (typeof optsOrFn !== "function") { + genFn = newGenerator(optsOrFn); + } else { + genFn = wrapGenerator(optsOrFn); + } + + return Object.assign(genFn, makeFunctionAPI(genFn)); + }, + { + all: buildOperation({ + name: "all", + arity: 1, + sync: function(args) { + const items = Array.from(args[0]); + return items.map(item => evaluateSync(item)); + }, + async: function(args, resolve, reject) { + const items = Array.from(args[0]); + + if (items.length === 0) { + Promise.resolve().then(() => resolve([])); + return; + } + + let count = 0; + const results = items.map(() => undefined); + items.forEach((item, i) => { + evaluateAsync( + item, + val => { + results[i] = val; + count += 1; + + if (count === results.length) resolve(results); + }, + reject + ); + }); + }, + }), + race: buildOperation({ + name: "race", + arity: 1, + sync: function(args) { + const items = Array.from(args[0]); + if (items.length === 0) { + throw makeError("Must race at least 1 item", GENSYNC_RACE_NONEMPTY); + } + + return evaluateSync(items[0]); + }, + async: function(args, resolve, reject) { + const items = Array.from(args[0]); + if (items.length === 0) { + throw makeError("Must race at least 1 item", GENSYNC_RACE_NONEMPTY); + } + + for (const item of items) { + evaluateAsync(item, resolve, reject); + } + }, + }), + } + ); + + /** + * Given a generator function, return the standard API object that executes + * the generator and calls the callbacks. + */ + function makeFunctionAPI(genFn) { + const fns = { + sync: function(...args) { + return evaluateSync(genFn.apply(this, args)); + }, + async: function(...args) { + return new Promise((resolve, reject) => { + evaluateAsync(genFn.apply(this, args), resolve, reject); + }); + }, + errback: function(...args) { + const cb = args.pop(); + if (typeof cb !== "function") { + throw makeError( + "Asynchronous function called without callback", + GENSYNC_ERRBACK_NO_CALLBACK + ); + } + + let gen; + try { + gen = genFn.apply(this, args); + } catch (err) { + cb(err); + return; + } + + evaluateAsync(gen, val => cb(undefined, val), err => cb(err)); + }, + }; + return fns; + } + + function assertTypeof(type, name, value, allowUndefined) { + if ( + typeof value === type || + (allowUndefined && typeof value === "undefined") + ) { + return; + } + + let msg; + if (allowUndefined) { + msg = `Expected opts.${name} to be either a ${type}, or undefined.`; + } else { + msg = `Expected opts.${name} to be a ${type}.`; + } + + throw makeError(msg, GENSYNC_OPTIONS_ERROR); + } + function makeError(msg, code) { + return Object.assign(new Error(msg), { code }); + } + + /** + * Given an options object, return a new generator that dispatches the + * correct handler based on sync or async execution. + */ + function newGenerator({ name, arity, sync, async, errback }) { + assertTypeof("string", "name", name, true /* allowUndefined */); + assertTypeof("number", "arity", arity, true /* allowUndefined */); + assertTypeof("function", "sync", sync); + assertTypeof("function", "async", async, true /* allowUndefined */); + assertTypeof("function", "errback", errback, true /* allowUndefined */); + if (async && errback) { + throw makeError( + "Expected one of either opts.async or opts.errback, but got _both_.", + GENSYNC_OPTIONS_ERROR + ); + } + + if (typeof name !== "string") { + let fnName; + if (errback && errback.name && errback.name !== "errback") { + fnName = errback.name; + } + if (async && async.name && async.name !== "async") { + fnName = async.name.replace(/Async$/, ""); + } + if (sync && sync.name && sync.name !== "sync") { + fnName = sync.name.replace(/Sync$/, ""); + } + + if (typeof fnName === "string") { + name = fnName; + } + } + + if (typeof arity !== "number") { + arity = sync.length; + } + + return buildOperation({ + name, + arity, + sync: function(args) { + return sync.apply(this, args); + }, + async: function(args, resolve, reject) { + if (async) { + async.apply(this, args).then(resolve, reject); + } else if (errback) { + errback.call(this, ...args, (err, value) => { + if (err == null) resolve(value); + else reject(err); + }); + } else { + resolve(sync.apply(this, args)); + } + }, + }); + } + + function wrapGenerator(genFn) { + return setFunctionMetadata(genFn.name, genFn.length, function(...args) { + return genFn.apply(this, args); + }); + } + + function buildOperation({ name, arity, sync, async }) { + return setFunctionMetadata(name, arity, function*(...args) { + const resume = yield GENSYNC_START; + if (!resume) { + // Break the tail call to avoid a bug in V8 v6.X with --harmony enabled. + const res = sync.call(this, args); + return res; + } + + let result; + try { + async.call( + this, + args, + value => { + if (result) return; + + result = { value }; + resume(); + }, + err => { + if (result) return; + + result = { err }; + resume(); + } + ); + } catch (err) { + result = { err }; + resume(); + } + + // Suspend until the callbacks run. Will resume synchronously if the + // callback was already called. + yield GENSYNC_SUSPEND; + + if (result.hasOwnProperty("err")) { + throw result.err; + } + + return result.value; + }); + } + + function evaluateSync(gen) { + let value; + while (!({ value } = gen.next()).done) { + assertStart(value, gen); + } + return value; + } + + function evaluateAsync(gen, resolve, reject) { + (function step() { + try { + let value; + while (!({ value } = gen.next()).done) { + assertStart(value, gen); + + // If this throws, it is considered to have broken the contract + // established for async handlers. If these handlers are called + // synchronously, it is also considered bad behavior. + let sync = true; + let didSyncResume = false; + const out = gen.next(() => { + if (sync) { + didSyncResume = true; + } else { + step(); + } + }); + sync = false; + + assertSuspend(out, gen); + + if (!didSyncResume) { + // Callback wasn't called synchronously, so break out of the loop + // and let it call 'step' later. + return; + } + } + + return resolve(value); + } catch (err) { + return reject(err); + } + })(); + } + + function assertStart(value, gen) { + if (value === GENSYNC_START) return; + + throwError( + gen, + makeError( + `Got unexpected yielded value in gensync generator: ${JSON.stringify( + value + )}. Did you perhaps mean to use 'yield*' instead of 'yield'?`, + GENSYNC_EXPECTED_START + ) + ); + } + function assertSuspend({ value, done }, gen) { + if (!done && value === GENSYNC_SUSPEND) return; + + throwError( + gen, + makeError( + done + ? "Unexpected generator completion. If you get this, it is probably a gensync bug." + : `Expected GENSYNC_SUSPEND, got ${JSON.stringify( + value + )}. If you get this, it is probably a gensync bug.`, + GENSYNC_EXPECTED_SUSPEND + ) + ); + } + + function throwError(gen, err) { + // Call `.throw` so that users can step in a debugger to easily see which + // 'yield' passed an unexpected value. If the `.throw` call didn't throw + // back to the generator, we explicitly do it to stop the error + // from being swallowed by user code try/catches. + if (gen.throw) gen.throw(err); + throw err; + } + + function setFunctionMetadata(name, arity, fn) { + if (typeof name === "string") { + // This should always work on the supported Node versions, but for the + // sake of users that are compiling to older versions, we check for + // configurability so we don't throw. + const nameDesc = Object.getOwnPropertyDescriptor(fn, "name"); + if (!nameDesc || nameDesc.configurable) { + Object.defineProperty( + fn, + "name", + Object.assign(nameDesc || {}, { + configurable: true, + value: name, + }) + ); + } + } + + if (typeof arity === "number") { + const lengthDesc = Object.getOwnPropertyDescriptor(fn, "length"); + if (!lengthDesc || lengthDesc.configurable) { + Object.defineProperty( + fn, + "length", + Object.assign(lengthDesc || {}, { + configurable: true, + value: arity, + }) + ); + } + } + + return fn; + } + + var async = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.maybeAsync = maybeAsync; + exports.forwardAsync = forwardAsync; + exports.isThenable = isThenable; + exports.waitFor = exports.onFirstPause = exports.isAsync = void 0; + + function _gensync() { + const data = _interopRequireDefault(gensync); + + _gensync = function () { + return data; + }; + + return data; + } + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + const id = x => x; + + const runGenerator = (0, _gensync().default)(function* (item) { + return yield* item; + }); + const isAsync = (0, _gensync().default)({ + sync: () => false, + errback: cb => cb(null, true) + }); + exports.isAsync = isAsync; + + function maybeAsync(fn, message) { + return (0, _gensync().default)({ + sync(...args) { + const result = fn.apply(this, args); + if (isThenable(result)) throw new Error(message); + return result; + }, + + async(...args) { + return Promise.resolve(fn.apply(this, args)); + } + + }); + } + + const withKind = (0, _gensync().default)({ + sync: cb => cb("sync"), + async: cb => cb("async") + }); + + function forwardAsync(action, cb) { + const g = (0, _gensync().default)(action); + return withKind(kind => { + const adapted = g[kind]; + return cb(adapted); + }); + } + + const onFirstPause = (0, _gensync().default)({ + name: "onFirstPause", + arity: 2, + sync: function (item) { + return runGenerator.sync(item); + }, + errback: function (item, firstPause, cb) { + let completed = false; + runGenerator.errback(item, (err, value) => { + completed = true; + cb(err, value); + }); + + if (!completed) { + firstPause(); + } + } + }); + exports.onFirstPause = onFirstPause; + const waitFor = (0, _gensync().default)({ + sync: id, + async: id + }); + exports.waitFor = waitFor; + + function isThenable(val) { + return !!val && (typeof val === "object" || typeof val === "function") && !!val.then && typeof val.then === "function"; + } + }); + + unwrapExports(async); + var async_1 = async.maybeAsync; + var async_2 = async.forwardAsync; + var async_3 = async.isThenable; + var async_4 = async.waitFor; + var async_5 = async.onFirstPause; + var async_6 = async.isAsync; + + var util$4 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.mergeOptions = mergeOptions; + exports.isIterableIterator = isIterableIterator; + + function mergeOptions(target, source) { + for (const k of Object.keys(source)) { + if (k === "parserOpts" && source.parserOpts) { + const parserOpts = source.parserOpts; + const targetObj = target.parserOpts = target.parserOpts || {}; + mergeDefaultFields(targetObj, parserOpts); + } else if (k === "generatorOpts" && source.generatorOpts) { + const generatorOpts = source.generatorOpts; + const targetObj = target.generatorOpts = target.generatorOpts || {}; + mergeDefaultFields(targetObj, generatorOpts); + } else { + const val = source[k]; + if (val !== undefined) target[k] = val; + } + } + } + + function mergeDefaultFields(target, source) { + for (const k of Object.keys(source)) { + const val = source[k]; + if (val !== undefined) target[k] = val; + } + } + + function isIterableIterator(value) { + return !!value && typeof value.next === "function" && typeof value[Symbol.iterator] === "function"; + } + }); + + unwrapExports(util$4); + var util_1$1 = util$4.mergeOptions; + var util_2$1 = util$4.isIterableIterator; + + var caching = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.makeWeakCache = makeWeakCache; + exports.makeWeakCacheSync = makeWeakCacheSync; + exports.makeStrongCache = makeStrongCache; + exports.makeStrongCacheSync = makeStrongCacheSync; + exports.assertSimpleType = assertSimpleType; + + function _gensync() { + const data = _interopRequireDefault(gensync); + + _gensync = function () { + return data; + }; + + return data; + } + + + + + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + const synchronize = gen => { + return (0, _gensync().default)(gen).sync; + }; + + function* genTrue(data) { + return true; + } + + function makeWeakCache(handler) { + return makeCachedFunction(WeakMap, handler); + } + + function makeWeakCacheSync(handler) { + return synchronize(makeWeakCache(handler)); + } + + function makeStrongCache(handler) { + return makeCachedFunction(Map, handler); + } + + function makeStrongCacheSync(handler) { + return synchronize(makeStrongCache(handler)); + } + + function makeCachedFunction(CallCache, handler) { + const callCacheSync = new CallCache(); + const callCacheAsync = new CallCache(); + const futureCache = new CallCache(); + return function* cachedFunction(arg, data) { + const asyncContext = yield* (0, async.isAsync)(); + const callCache = asyncContext ? callCacheAsync : callCacheSync; + const cached = yield* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data); + if (cached.valid) return cached.value; + const cache = new CacheConfigurator(data); + const handlerResult = handler(arg, cache); + let finishLock; + let value; + + if ((0, util$4.isIterableIterator)(handlerResult)) { + const gen = handlerResult; + value = yield* (0, async.onFirstPause)(gen, () => { + finishLock = setupAsyncLocks(cache, futureCache, arg); + }); + } else { + value = handlerResult; + } + + updateFunctionCache(callCache, cache, arg, value); + + if (finishLock) { + futureCache.delete(arg); + finishLock.release(value); + } + + return value; + }; + } + + function* getCachedValue(cache, arg, data) { + const cachedValue = cache.get(arg); + + if (cachedValue) { + for (const { + value, + valid + } of cachedValue) { + if (yield* valid(data)) return { + valid: true, + value + }; + } + } + + return { + valid: false, + value: null + }; + } + + function* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data) { + const cached = yield* getCachedValue(callCache, arg, data); + + if (cached.valid) { + return cached; + } + + if (asyncContext) { + const cached = yield* getCachedValue(futureCache, arg, data); + + if (cached.valid) { + const value = yield* (0, async.waitFor)(cached.value.promise); + return { + valid: true, + value + }; + } + } + + return { + valid: false, + value: null + }; + } + + function setupAsyncLocks(config, futureCache, arg) { + const finishLock = new Lock(); + updateFunctionCache(futureCache, config, arg, finishLock); + return finishLock; + } + + function updateFunctionCache(cache, config, arg, value) { + if (!config.configured()) config.forever(); + let cachedValue = cache.get(arg); + config.deactivate(); + + switch (config.mode()) { + case "forever": + cachedValue = [{ + value, + valid: genTrue + }]; + cache.set(arg, cachedValue); + break; + + case "invalidate": + cachedValue = [{ + value, + valid: config.validator() + }]; + cache.set(arg, cachedValue); + break; + + case "valid": + if (cachedValue) { + cachedValue.push({ + value, + valid: config.validator() + }); + } else { + cachedValue = [{ + value, + valid: config.validator() + }]; + cache.set(arg, cachedValue); + } + + } + } + + class CacheConfigurator { + constructor(data) { + this._active = true; + this._never = false; + this._forever = false; + this._invalidate = false; + this._configured = false; + this._pairs = []; + this._data = void 0; + this._data = data; + } + + simple() { + return makeSimpleConfigurator(this); + } + + mode() { + if (this._never) return "never"; + if (this._forever) return "forever"; + if (this._invalidate) return "invalidate"; + return "valid"; + } + + forever() { + if (!this._active) { + throw new Error("Cannot change caching after evaluation has completed."); + } + + if (this._never) { + throw new Error("Caching has already been configured with .never()"); + } + + this._forever = true; + this._configured = true; + } + + never() { + if (!this._active) { + throw new Error("Cannot change caching after evaluation has completed."); + } + + if (this._forever) { + throw new Error("Caching has already been configured with .forever()"); + } + + this._never = true; + this._configured = true; + } + + using(handler) { + if (!this._active) { + throw new Error("Cannot change caching after evaluation has completed."); + } + + if (this._never || this._forever) { + throw new Error("Caching has already been configured with .never or .forever()"); + } + + this._configured = true; + const key = handler(this._data); + const fn = (0, async.maybeAsync)(handler, `You appear to be using an async cache handler, but Babel has been called synchronously`); + + if ((0, async.isThenable)(key)) { + return key.then(key => { + this._pairs.push([key, fn]); + + return key; + }); + } + + this._pairs.push([key, fn]); + + return key; + } + + invalidate(handler) { + this._invalidate = true; + return this.using(handler); + } + + validator() { + const pairs = this._pairs; + return function* (data) { + for (const [key, fn] of pairs) { + if (key !== (yield* fn(data))) return false; + } + + return true; + }; + } + + deactivate() { + this._active = false; + } + + configured() { + return this._configured; + } + + } + + function makeSimpleConfigurator(cache) { + function cacheFn(val) { + if (typeof val === "boolean") { + if (val) cache.forever();else cache.never(); + return; + } + + return cache.using(() => assertSimpleType(val())); + } + + cacheFn.forever = () => cache.forever(); + + cacheFn.never = () => cache.never(); + + cacheFn.using = cb => cache.using(() => assertSimpleType(cb())); + + cacheFn.invalidate = cb => cache.invalidate(() => assertSimpleType(cb())); + + return cacheFn; + } + + function assertSimpleType(value) { + if ((0, async.isThenable)(value)) { + throw new Error(`You appear to be using an async cache handler, ` + `which your current version of Babel does not support. ` + `We may add support for this in the future, ` + `but if you're on the most recent version of @babel/core and still ` + `seeing this error, then you'll need to synchronously handle your caching logic.`); + } + + if (value != null && typeof value !== "string" && typeof value !== "boolean" && typeof value !== "number") { + throw new Error("Cache keys must be either string, boolean, number, null, or undefined."); + } + + return value; + } + + class Lock { + constructor() { + this.released = false; + this.promise = void 0; + this._resolve = void 0; + this.promise = new Promise(resolve => { + this._resolve = resolve; + }); + } + + release(value) { + this.released = true; + + this._resolve(value); + } + + } + }); + + unwrapExports(caching); + var caching_1 = caching.makeWeakCache; + var caching_2 = caching.makeWeakCacheSync; + var caching_3 = caching.makeStrongCache; + var caching_4 = caching.makeStrongCacheSync; + var caching_5 = caching.assertSimpleType; + + var require$$0$1 = {}; + + var fs = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.stat = exports.exists = exports.readFile = void 0; + + function _fs() { + const data = _interopRequireDefault(require$$0$1); + + _fs = function () { + return data; + }; + + return data; + } + + function _gensync() { + const data = _interopRequireDefault(gensync); + + _gensync = function () { + return data; + }; + + return data; + } + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + const readFile = (0, _gensync().default)({ + sync: _fs().default.readFileSync, + errback: _fs().default.readFile + }); + exports.readFile = readFile; + const exists = (0, _gensync().default)({ + sync(path) { + try { + _fs().default.accessSync(path); + + return true; + } catch (_unused) { + return false; + } + }, + + errback: (path, cb) => _fs().default.access(path, undefined, err => cb(null, !err)) + }); + exports.exists = exists; + const stat = (0, _gensync().default)({ + sync: _fs().default.statSync, + errback: _fs().default.stat + }); + exports.stat = stat; + }); + + unwrapExports(fs); + var fs_1 = fs.stat; + var fs_2 = fs.exists; + var fs_3 = fs.readFile; + + var utils$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.makeStaticFileCache = makeStaticFileCache; + + + + var fs$1 = _interopRequireWildcard(fs); + + function _fs2() { + const data = _interopRequireDefault(require$$0$1); + + _fs2 = function () { + return data; + }; + + return data; + } + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + function makeStaticFileCache(fn) { + return (0, caching.makeStrongCache)(function* (filepath, cache) { + const cached = cache.invalidate(() => fileMtime(filepath)); + + if (cached === null) { + return null; + } + + return fn(filepath, yield* fs$1.readFile(filepath, "utf8")); + }); + } + + function fileMtime(filepath) { + try { + return +_fs2().default.statSync(filepath).mtime; + } catch (e) { + if (e.code !== "ENOENT" && e.code !== "ENOTDIR") throw e; + } + + return null; + } + }); + + unwrapExports(utils$1); + var utils_1$1 = utils$1.makeStaticFileCache; + + var _package = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.findPackageData = findPackageData; + + function _path() { + const data = _interopRequireDefault(require$$1); + + _path = function () { + return data; + }; + + return data; + } + + + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + const PACKAGE_FILENAME = "package.json"; + + function* findPackageData(filepath) { + let pkg = null; + const directories = []; + let isPackage = true; + + let dirname = _path().default.dirname(filepath); + + while (!pkg && _path().default.basename(dirname) !== "node_modules") { + directories.push(dirname); + pkg = yield* readConfigPackage(_path().default.join(dirname, PACKAGE_FILENAME)); + + const nextLoc = _path().default.dirname(dirname); + + if (dirname === nextLoc) { + isPackage = false; + break; + } + + dirname = nextLoc; + } + + return { + filepath, + directories, + pkg, + isPackage + }; + } + + const readConfigPackage = (0, utils$1.makeStaticFileCache)((filepath, content) => { + let options; + + try { + options = JSON.parse(content); + } catch (err) { + err.message = `${filepath}: Error while parsing JSON - ${err.message}`; + throw err; + } + + if (!options) throw new Error(`${filepath}: No config detected`); + + if (typeof options !== "object") { + throw new Error(`${filepath}: Config returned typeof ${typeof options}`); + } + + if (Array.isArray(options)) { + throw new Error(`${filepath}: Expected config object but found array`); + } + + return { + filepath, + dirname: _path().default.dirname(filepath), + options + }; + }); + }); + + unwrapExports(_package); + var _package_1 = _package.findPackageData; + + // This is a generated file. Do not edit. + var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/; + var ID_Start = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/; + var ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/; + + var unicode = { + Space_Separator: Space_Separator, + ID_Start: ID_Start, + ID_Continue: ID_Continue + }; + + var util$5 = { + isSpaceSeparator (c) { + return typeof c === 'string' && unicode.Space_Separator.test(c) + }, + + isIdStartChar (c) { + return typeof c === 'string' && ( + (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c === '$') || (c === '_') || + unicode.ID_Start.test(c) + ) + }, + + isIdContinueChar (c) { + return typeof c === 'string' && ( + (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || + (c === '$') || (c === '_') || + (c === '\u200C') || (c === '\u200D') || + unicode.ID_Continue.test(c) + ) + }, + + isDigit (c) { + return typeof c === 'string' && /[0-9]/.test(c) + }, + + isHexDigit (c) { + return typeof c === 'string' && /[0-9A-Fa-f]/.test(c) + }, + }; + + let source; + let parseState; + let stack; + let pos; + let line; + let column; + let token; + let key; + let root$1; + + var parse$2 = function parse (text, reviver) { + source = String(text); + parseState = 'start'; + stack = []; + pos = 0; + line = 1; + column = 0; + token = undefined; + key = undefined; + root$1 = undefined; + + do { + token = lex(); + + // This code is unreachable. + // if (!parseStates[parseState]) { + // throw invalidParseState() + // } + + parseStates[parseState](); + } while (token.type !== 'eof') + + if (typeof reviver === 'function') { + return internalize({'': root$1}, '', reviver) + } + + return root$1 + }; + + function internalize (holder, name, reviver) { + const value = holder[name]; + if (value != null && typeof value === 'object') { + for (const key in value) { + const replacement = internalize(value, key, reviver); + if (replacement === undefined) { + delete value[key]; + } else { + value[key] = replacement; + } + } + } + + return reviver.call(holder, name, value) + } + + let lexState; + let buffer$1; + let doubleQuote; + let sign; + let c; + + function lex () { + lexState = 'default'; + buffer$1 = ''; + doubleQuote = false; + sign = 1; + + for (;;) { + c = peek(); + + // This code is unreachable. + // if (!lexStates[lexState]) { + // throw invalidLexState(lexState) + // } + + const token = lexStates[lexState](); + if (token) { + return token + } + } + } + + function peek () { + if (source[pos]) { + return String.fromCodePoint(source.codePointAt(pos)) + } + } + + function read$1 () { + const c = peek(); + + if (c === '\n') { + line++; + column = 0; + } else if (c) { + column += c.length; + } else { + column++; + } + + if (c) { + pos += c.length; + } + + return c + } + + const lexStates = { + default () { + switch (c) { + case '\t': + case '\v': + case '\f': + case ' ': + case '\u00A0': + case '\uFEFF': + case '\n': + case '\r': + case '\u2028': + case '\u2029': + read$1(); + return + + case '/': + read$1(); + lexState = 'comment'; + return + + case undefined: + read$1(); + return newToken('eof') + } + + if (util$5.isSpaceSeparator(c)) { + read$1(); + return + } + + // This code is unreachable. + // if (!lexStates[parseState]) { + // throw invalidLexState(parseState) + // } + + return lexStates[parseState]() + }, + + comment () { + switch (c) { + case '*': + read$1(); + lexState = 'multiLineComment'; + return + + case '/': + read$1(); + lexState = 'singleLineComment'; + return + } + + throw invalidChar(read$1()) + }, + + multiLineComment () { + switch (c) { + case '*': + read$1(); + lexState = 'multiLineCommentAsterisk'; + return + + case undefined: + throw invalidChar(read$1()) + } + + read$1(); + }, + + multiLineCommentAsterisk () { + switch (c) { + case '*': + read$1(); + return + + case '/': + read$1(); + lexState = 'default'; + return + + case undefined: + throw invalidChar(read$1()) + } + + read$1(); + lexState = 'multiLineComment'; + }, + + singleLineComment () { + switch (c) { + case '\n': + case '\r': + case '\u2028': + case '\u2029': + read$1(); + lexState = 'default'; + return + + case undefined: + read$1(); + return newToken('eof') + } + + read$1(); + }, + + value () { + switch (c) { + case '{': + case '[': + return newToken('punctuator', read$1()) + + case 'n': + read$1(); + literal$1('ull'); + return newToken('null', null) + + case 't': + read$1(); + literal$1('rue'); + return newToken('boolean', true) + + case 'f': + read$1(); + literal$1('alse'); + return newToken('boolean', false) + + case '-': + case '+': + if (read$1() === '-') { + sign = -1; + } + + lexState = 'sign'; + return + + case '.': + buffer$1 = read$1(); + lexState = 'decimalPointLeading'; + return + + case '0': + buffer$1 = read$1(); + lexState = 'zero'; + return + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + buffer$1 = read$1(); + lexState = 'decimalInteger'; + return + + case 'I': + read$1(); + literal$1('nfinity'); + return newToken('numeric', Infinity) + + case 'N': + read$1(); + literal$1('aN'); + return newToken('numeric', NaN) + + case '"': + case "'": + doubleQuote = (read$1() === '"'); + buffer$1 = ''; + lexState = 'string'; + return + } + + throw invalidChar(read$1()) + }, + + identifierNameStartEscape () { + if (c !== 'u') { + throw invalidChar(read$1()) + } + + read$1(); + const u = unicodeEscape(); + switch (u) { + case '$': + case '_': + break + + default: + if (!util$5.isIdStartChar(u)) { + throw invalidIdentifier() + } + + break + } + + buffer$1 += u; + lexState = 'identifierName'; + }, + + identifierName () { + switch (c) { + case '$': + case '_': + case '\u200C': + case '\u200D': + buffer$1 += read$1(); + return + + case '\\': + read$1(); + lexState = 'identifierNameEscape'; + return + } + + if (util$5.isIdContinueChar(c)) { + buffer$1 += read$1(); + return + } + + return newToken('identifier', buffer$1) + }, + + identifierNameEscape () { + if (c !== 'u') { + throw invalidChar(read$1()) + } + + read$1(); + const u = unicodeEscape(); + switch (u) { + case '$': + case '_': + case '\u200C': + case '\u200D': + break + + default: + if (!util$5.isIdContinueChar(u)) { + throw invalidIdentifier() + } + + break + } + + buffer$1 += u; + lexState = 'identifierName'; + }, + + sign () { + switch (c) { + case '.': + buffer$1 = read$1(); + lexState = 'decimalPointLeading'; + return + + case '0': + buffer$1 = read$1(); + lexState = 'zero'; + return + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + buffer$1 = read$1(); + lexState = 'decimalInteger'; + return + + case 'I': + read$1(); + literal$1('nfinity'); + return newToken('numeric', sign * Infinity) + + case 'N': + read$1(); + literal$1('aN'); + return newToken('numeric', NaN) + } + + throw invalidChar(read$1()) + }, + + zero () { + switch (c) { + case '.': + buffer$1 += read$1(); + lexState = 'decimalPoint'; + return + + case 'e': + case 'E': + buffer$1 += read$1(); + lexState = 'decimalExponent'; + return + + case 'x': + case 'X': + buffer$1 += read$1(); + lexState = 'hexadecimal'; + return + } + + return newToken('numeric', sign * 0) + }, + + decimalInteger () { + switch (c) { + case '.': + buffer$1 += read$1(); + lexState = 'decimalPoint'; + return + + case 'e': + case 'E': + buffer$1 += read$1(); + lexState = 'decimalExponent'; + return + } + + if (util$5.isDigit(c)) { + buffer$1 += read$1(); + return + } + + return newToken('numeric', sign * Number(buffer$1)) + }, + + decimalPointLeading () { + if (util$5.isDigit(c)) { + buffer$1 += read$1(); + lexState = 'decimalFraction'; + return + } + + throw invalidChar(read$1()) + }, + + decimalPoint () { + switch (c) { + case 'e': + case 'E': + buffer$1 += read$1(); + lexState = 'decimalExponent'; + return + } + + if (util$5.isDigit(c)) { + buffer$1 += read$1(); + lexState = 'decimalFraction'; + return + } + + return newToken('numeric', sign * Number(buffer$1)) + }, + + decimalFraction () { + switch (c) { + case 'e': + case 'E': + buffer$1 += read$1(); + lexState = 'decimalExponent'; + return + } + + if (util$5.isDigit(c)) { + buffer$1 += read$1(); + return + } + + return newToken('numeric', sign * Number(buffer$1)) + }, + + decimalExponent () { + switch (c) { + case '+': + case '-': + buffer$1 += read$1(); + lexState = 'decimalExponentSign'; + return + } + + if (util$5.isDigit(c)) { + buffer$1 += read$1(); + lexState = 'decimalExponentInteger'; + return + } + + throw invalidChar(read$1()) + }, + + decimalExponentSign () { + if (util$5.isDigit(c)) { + buffer$1 += read$1(); + lexState = 'decimalExponentInteger'; + return + } + + throw invalidChar(read$1()) + }, + + decimalExponentInteger () { + if (util$5.isDigit(c)) { + buffer$1 += read$1(); + return + } + + return newToken('numeric', sign * Number(buffer$1)) + }, + + hexadecimal () { + if (util$5.isHexDigit(c)) { + buffer$1 += read$1(); + lexState = 'hexadecimalInteger'; + return + } + + throw invalidChar(read$1()) + }, + + hexadecimalInteger () { + if (util$5.isHexDigit(c)) { + buffer$1 += read$1(); + return + } + + return newToken('numeric', sign * Number(buffer$1)) + }, + + string () { + switch (c) { + case '\\': + read$1(); + buffer$1 += escape$1(); + return + + case '"': + if (doubleQuote) { + read$1(); + return newToken('string', buffer$1) + } + + buffer$1 += read$1(); + return + + case "'": + if (!doubleQuote) { + read$1(); + return newToken('string', buffer$1) + } + + buffer$1 += read$1(); + return + + case '\n': + case '\r': + throw invalidChar(read$1()) + + case '\u2028': + case '\u2029': + separatorChar(c); + break + + case undefined: + throw invalidChar(read$1()) + } + + buffer$1 += read$1(); + }, + + start () { + switch (c) { + case '{': + case '[': + return newToken('punctuator', read$1()) + + // This code is unreachable since the default lexState handles eof. + // case undefined: + // return newToken('eof') + } + + lexState = 'value'; + }, + + beforePropertyName () { + switch (c) { + case '$': + case '_': + buffer$1 = read$1(); + lexState = 'identifierName'; + return + + case '\\': + read$1(); + lexState = 'identifierNameStartEscape'; + return + + case '}': + return newToken('punctuator', read$1()) + + case '"': + case "'": + doubleQuote = (read$1() === '"'); + lexState = 'string'; + return + } + + if (util$5.isIdStartChar(c)) { + buffer$1 += read$1(); + lexState = 'identifierName'; + return + } + + throw invalidChar(read$1()) + }, + + afterPropertyName () { + if (c === ':') { + return newToken('punctuator', read$1()) + } + + throw invalidChar(read$1()) + }, + + beforePropertyValue () { + lexState = 'value'; + }, + + afterPropertyValue () { + switch (c) { + case ',': + case '}': + return newToken('punctuator', read$1()) + } + + throw invalidChar(read$1()) + }, + + beforeArrayValue () { + if (c === ']') { + return newToken('punctuator', read$1()) + } + + lexState = 'value'; + }, + + afterArrayValue () { + switch (c) { + case ',': + case ']': + return newToken('punctuator', read$1()) + } + + throw invalidChar(read$1()) + }, + + end () { + // This code is unreachable since it's handled by the default lexState. + // if (c === undefined) { + // read() + // return newToken('eof') + // } + + throw invalidChar(read$1()) + }, + }; + + function newToken (type, value) { + return { + type, + value, + line, + column, + } + } + + function literal$1 (s) { + for (const c of s) { + const p = peek(); + + if (p !== c) { + throw invalidChar(read$1()) + } + + read$1(); + } + } + + function escape$1 () { + const c = peek(); + switch (c) { + case 'b': + read$1(); + return '\b' + + case 'f': + read$1(); + return '\f' + + case 'n': + read$1(); + return '\n' + + case 'r': + read$1(); + return '\r' + + case 't': + read$1(); + return '\t' + + case 'v': + read$1(); + return '\v' + + case '0': + read$1(); + if (util$5.isDigit(peek())) { + throw invalidChar(read$1()) + } + + return '\0' + + case 'x': + read$1(); + return hexEscape() + + case 'u': + read$1(); + return unicodeEscape() + + case '\n': + case '\u2028': + case '\u2029': + read$1(); + return '' + + case '\r': + read$1(); + if (peek() === '\n') { + read$1(); + } + + return '' + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + throw invalidChar(read$1()) + + case undefined: + throw invalidChar(read$1()) + } + + return read$1() + } + + function hexEscape () { + let buffer = ''; + let c = peek(); + + if (!util$5.isHexDigit(c)) { + throw invalidChar(read$1()) + } + + buffer += read$1(); + + c = peek(); + if (!util$5.isHexDigit(c)) { + throw invalidChar(read$1()) + } + + buffer += read$1(); + + return String.fromCodePoint(parseInt(buffer, 16)) + } + + function unicodeEscape () { + let buffer = ''; + let count = 4; + + while (count-- > 0) { + const c = peek(); + if (!util$5.isHexDigit(c)) { + throw invalidChar(read$1()) + } + + buffer += read$1(); + } + + return String.fromCodePoint(parseInt(buffer, 16)) + } + + const parseStates = { + start () { + if (token.type === 'eof') { + throw invalidEOF() + } + + push(); + }, + + beforePropertyName () { + switch (token.type) { + case 'identifier': + case 'string': + key = token.value; + parseState = 'afterPropertyName'; + return + + case 'punctuator': + // This code is unreachable since it's handled by the lexState. + // if (token.value !== '}') { + // throw invalidToken() + // } + + pop(); + return + + case 'eof': + throw invalidEOF() + } + + // This code is unreachable since it's handled by the lexState. + // throw invalidToken() + }, + + afterPropertyName () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'punctuator' || token.value !== ':') { + // throw invalidToken() + // } + + if (token.type === 'eof') { + throw invalidEOF() + } + + parseState = 'beforePropertyValue'; + }, + + beforePropertyValue () { + if (token.type === 'eof') { + throw invalidEOF() + } + + push(); + }, + + beforeArrayValue () { + if (token.type === 'eof') { + throw invalidEOF() + } + + if (token.type === 'punctuator' && token.value === ']') { + pop(); + return + } + + push(); + }, + + afterPropertyValue () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'punctuator') { + // throw invalidToken() + // } + + if (token.type === 'eof') { + throw invalidEOF() + } + + switch (token.value) { + case ',': + parseState = 'beforePropertyName'; + return + + case '}': + pop(); + } + + // This code is unreachable since it's handled by the lexState. + // throw invalidToken() + }, + + afterArrayValue () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'punctuator') { + // throw invalidToken() + // } + + if (token.type === 'eof') { + throw invalidEOF() + } + + switch (token.value) { + case ',': + parseState = 'beforeArrayValue'; + return + + case ']': + pop(); + } + + // This code is unreachable since it's handled by the lexState. + // throw invalidToken() + }, + + end () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'eof') { + // throw invalidToken() + // } + }, + }; + + function push () { + let value; + + switch (token.type) { + case 'punctuator': + switch (token.value) { + case '{': + value = {}; + break + + case '[': + value = []; + break + } + + break + + case 'null': + case 'boolean': + case 'numeric': + case 'string': + value = token.value; + break + + // This code is unreachable. + // default: + // throw invalidToken() + } + + if (root$1 === undefined) { + root$1 = value; + } else { + const parent = stack[stack.length - 1]; + if (Array.isArray(parent)) { + parent.push(value); + } else { + parent[key] = value; + } + } + + if (value !== null && typeof value === 'object') { + stack.push(value); + + if (Array.isArray(value)) { + parseState = 'beforeArrayValue'; + } else { + parseState = 'beforePropertyName'; + } + } else { + const current = stack[stack.length - 1]; + if (current == null) { + parseState = 'end'; + } else if (Array.isArray(current)) { + parseState = 'afterArrayValue'; + } else { + parseState = 'afterPropertyValue'; + } + } + } + + function pop () { + stack.pop(); + + const current = stack[stack.length - 1]; + if (current == null) { + parseState = 'end'; + } else if (Array.isArray(current)) { + parseState = 'afterArrayValue'; + } else { + parseState = 'afterPropertyValue'; + } + } + + // This code is unreachable. + // function invalidParseState () { + // return new Error(`JSON5: invalid parse state '${parseState}'`) + // } + + // This code is unreachable. + // function invalidLexState (state) { + // return new Error(`JSON5: invalid lex state '${state}'`) + // } + + function invalidChar (c) { + if (c === undefined) { + return syntaxError(`JSON5: invalid end of input at ${line}:${column}`) + } + + return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`) + } + + function invalidEOF () { + return syntaxError(`JSON5: invalid end of input at ${line}:${column}`) + } + + // This code is unreachable. + // function invalidToken () { + // if (token.type === 'eof') { + // return syntaxError(`JSON5: invalid end of input at ${line}:${column}`) + // } + + // const c = String.fromCodePoint(token.value.codePointAt(0)) + // return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`) + // } + + function invalidIdentifier () { + column -= 5; + return syntaxError(`JSON5: invalid identifier character at ${line}:${column}`) + } + + function separatorChar (c) { + console.warn(`JSON5: '${formatChar(c)}' in strings is not valid ECMAScript; consider escaping`); + } + + function formatChar (c) { + const replacements = { + "'": "\\'", + '"': '\\"', + '\\': '\\\\', + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t', + '\v': '\\v', + '\0': '\\0', + '\u2028': '\\u2028', + '\u2029': '\\u2029', + }; + + if (replacements[c]) { + return replacements[c] + } + + if (c < ' ') { + const hexString = c.charCodeAt(0).toString(16); + return '\\x' + ('00' + hexString).substring(hexString.length) + } + + return c + } + + function syntaxError (message) { + const err = new SyntaxError(message); + err.lineNumber = line; + err.columnNumber = column; + return err + } + + var stringify = function stringify (value, replacer, space) { + const stack = []; + let indent = ''; + let propertyList; + let replacerFunc; + let gap = ''; + let quote; + + if ( + replacer != null && + typeof replacer === 'object' && + !Array.isArray(replacer) + ) { + space = replacer.space; + quote = replacer.quote; + replacer = replacer.replacer; + } + + if (typeof replacer === 'function') { + replacerFunc = replacer; + } else if (Array.isArray(replacer)) { + propertyList = []; + for (const v of replacer) { + let item; + + if (typeof v === 'string') { + item = v; + } else if ( + typeof v === 'number' || + v instanceof String || + v instanceof Number + ) { + item = String(v); + } + + if (item !== undefined && propertyList.indexOf(item) < 0) { + propertyList.push(item); + } + } + } + + if (space instanceof Number) { + space = Number(space); + } else if (space instanceof String) { + space = String(space); + } + + if (typeof space === 'number') { + if (space > 0) { + space = Math.min(10, Math.floor(space)); + gap = ' '.substr(0, space); + } + } else if (typeof space === 'string') { + gap = space.substr(0, 10); + } + + return serializeProperty('', {'': value}) + + function serializeProperty (key, holder) { + let value = holder[key]; + if (value != null) { + if (typeof value.toJSON5 === 'function') { + value = value.toJSON5(key); + } else if (typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + } + + if (replacerFunc) { + value = replacerFunc.call(holder, key, value); + } + + if (value instanceof Number) { + value = Number(value); + } else if (value instanceof String) { + value = String(value); + } else if (value instanceof Boolean) { + value = value.valueOf(); + } + + switch (value) { + case null: return 'null' + case true: return 'true' + case false: return 'false' + } + + if (typeof value === 'string') { + return quoteString(value) + } + + if (typeof value === 'number') { + return String(value) + } + + if (typeof value === 'object') { + return Array.isArray(value) ? serializeArray(value) : serializeObject(value) + } + + return undefined + } + + function quoteString (value) { + const quotes = { + "'": 0.1, + '"': 0.2, + }; + + const replacements = { + "'": "\\'", + '"': '\\"', + '\\': '\\\\', + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t', + '\v': '\\v', + '\0': '\\0', + '\u2028': '\\u2028', + '\u2029': '\\u2029', + }; + + let product = ''; + + for (let i = 0; i < value.length; i++) { + const c = value[i]; + switch (c) { + case "'": + case '"': + quotes[c]++; + product += c; + continue + + case '\0': + if (util$5.isDigit(value[i + 1])) { + product += '\\x00'; + continue + } + } + + if (replacements[c]) { + product += replacements[c]; + continue + } + + if (c < ' ') { + let hexString = c.charCodeAt(0).toString(16); + product += '\\x' + ('00' + hexString).substring(hexString.length); + continue + } + + product += c; + } + + const quoteChar = quote || Object.keys(quotes).reduce((a, b) => (quotes[a] < quotes[b]) ? a : b); + + product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]); + + return quoteChar + product + quoteChar + } + + function serializeObject (value) { + if (stack.indexOf(value) >= 0) { + throw TypeError('Converting circular structure to JSON5') + } + + stack.push(value); + + let stepback = indent; + indent = indent + gap; + + let keys = propertyList || Object.keys(value); + let partial = []; + for (const key of keys) { + const propertyString = serializeProperty(key, value); + if (propertyString !== undefined) { + let member = serializeKey(key) + ':'; + if (gap !== '') { + member += ' '; + } + member += propertyString; + partial.push(member); + } + } + + let final; + if (partial.length === 0) { + final = '{}'; + } else { + let properties; + if (gap === '') { + properties = partial.join(','); + final = '{' + properties + '}'; + } else { + let separator = ',\n' + indent; + properties = partial.join(separator); + final = '{\n' + indent + properties + ',\n' + stepback + '}'; + } + } + + stack.pop(); + indent = stepback; + return final + } + + function serializeKey (key) { + if (key.length === 0) { + return quoteString(key) + } + + const firstChar = String.fromCodePoint(key.codePointAt(0)); + if (!util$5.isIdStartChar(firstChar)) { + return quoteString(key) + } + + for (let i = firstChar.length; i < key.length; i++) { + if (!util$5.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) { + return quoteString(key) + } + } + + return key + } + + function serializeArray (value) { + if (stack.indexOf(value) >= 0) { + throw TypeError('Converting circular structure to JSON5') + } + + stack.push(value); + + let stepback = indent; + indent = indent + gap; + + let partial = []; + for (let i = 0; i < value.length; i++) { + const propertyString = serializeProperty(String(i), value); + partial.push((propertyString !== undefined) ? propertyString : 'null'); + } + + let final; + if (partial.length === 0) { + final = '[]'; + } else { + if (gap === '') { + let properties = partial.join(','); + final = '[' + properties + ']'; + } else { + let separator = ',\n' + indent; + let properties = partial.join(separator); + final = '[\n' + indent + properties + ',\n' + stepback + ']'; + } + } + + stack.pop(); + indent = stepback; + return final + } + }; + + const JSON5 = { + parse: parse$2, + stringify, + }; + + var lib$i = JSON5; + + var dist = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': lib$i + }); + + var configApi = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = makeAPI; + + function _semver() { + const data = _interopRequireDefault(semver); + + _semver = function () { + return data; + }; + + return data; + } + + + + + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function makeAPI(cache) { + const env = value => cache.using(data => { + if (typeof value === "undefined") return data.envName; + + if (typeof value === "function") { + return (0, caching.assertSimpleType)(value(data.envName)); + } + + if (!Array.isArray(value)) value = [value]; + return value.some(entry => { + if (typeof entry !== "string") { + throw new Error("Unexpected non-string value"); + } + + return entry === data.envName; + }); + }); + + const caller = cb => cache.using(data => (0, caching.assertSimpleType)(cb(data.caller))); + + return { + version: lib$j.version, + cache: cache.simple(), + env, + async: () => false, + caller, + assertVersion + }; + } + + function assertVersion(range) { + if (typeof range === "number") { + if (!Number.isInteger(range)) { + throw new Error("Expected string or integer value."); + } + + range = `^${range}.0.0-0`; + } + + if (typeof range !== "string") { + throw new Error("Expected string or integer value."); + } + + if (_semver().default.satisfies(lib$j.version, range)) return; + const limit = Error.stackTraceLimit; + + if (typeof limit === "number" && limit < 25) { + Error.stackTraceLimit = 25; + } + + const err = new Error(`Requires Babel "${range}", but was loaded with "${lib$j.version}". ` + `If you are sure you have a compatible version of @babel/core, ` + `it is likely that something in your build process is loading the ` + `wrong version. Inspect the stack trace of this error to look for ` + `the first entry that doesn't mention "@babel/core" or "babel-core" ` + `to see what is calling Babel.`); + + if (typeof limit === "number") { + Error.stackTraceLimit = limit; + } + + throw Object.assign(err, { + code: "BABEL_VERSION_UNSUPPORTED", + version: lib$j.version, + range + }); + } + }); + + unwrapExports(configApi); + + /*! https://mths.be/punycode v1.4.1 by @mathias */ + + + /** Highest positive signed 32-bit float value */ + var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + var base$1 = 36; + var tMin = 1; + var tMax = 26; + var skew = 38; + var damp = 700; + var initialBias = 72; + var initialN = 128; // 0x80 + var delimiter$1 = '-'; // '\x2D' + var regexNonASCII = /[^\x20-\x7E]/; // unprintable ASCII chars + non-ASCII chars + var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + + /** Error messages */ + var errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }; + + /** Convenience shortcuts */ + var baseMinusTMin = base$1 - tMin; + var floor = Math.floor; + var stringFromCharCode = String.fromCharCode; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base$1) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode$2(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter$1); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base$1; /* no condition */ ; k += base$1) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base$1 - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) ? + 'xn--' + encode$2(string) : + string; + }); + } + + // 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. + + + // If obj.hasOwnProperty has been overridden, then calling + // obj.hasOwnProperty(prop) will break. + // See: https://github.com/joyent/node/issues/1707 + function hasOwnProperty$d(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + var isArray$4 = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; + }; + function stringifyPrimitive(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } + } + + function stringify$1 (obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map$1(objectKeys$1(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray$4(obj[k])) { + return map$1(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); + } + function map$1 (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; + } + + var objectKeys$1 = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; + }; + + function parse$3(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty$d(obj, k)) { + obj[k] = v; + } else if (isArray$4(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; + }var qs = { + encode: stringify$1, + stringify: stringify$1, + decode: parse$3, + parse: parse$3 + }; + + var qs$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + stringify: stringify$1, + parse: parse$3, + 'default': qs, + encode: stringify$1, + decode: parse$3 + }); + + // Copyright Joyent, Inc. and other Node contributors. + var url = { + parse: urlParse, + resolve: urlResolve, + resolveObject: urlResolveObject, + format: urlFormat, + Url: Url + }; + function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; + } + + // Reference: RFC 3986, RFC 1808, RFC 2396 + + // define these here so at least they only have to be + // compiled once on the first module load. + var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }; + + function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && isObject$1(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; + } + Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + return parse$4(this, url, parseQueryString, slashesDenoteHost); + }; + + function parse$4(self, url, parseQueryString, slashesDenoteHost) { + if (!isString(url)) { + throw new TypeError('Parameter \'url\' must be a string, not ' + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + self.path = rest; + self.href = rest; + self.pathname = simplePath[1]; + if (simplePath[2]) { + self.search = simplePath[2]; + if (parseQueryString) { + self.query = parse$3(self.search.substr(1)); + } else { + self.query = self.search.substr(1); + } + } else if (parseQueryString) { + self.search = ''; + self.query = {}; + } + return self; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + self.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + self.slashes = true; + } + } + var i, hec, l, p; + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (i = 0; i < hostEndingChars.length; i++) { + hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + self.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (i = 0; i < nonHostChars.length; i++) { + hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + self.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + parseHost(self); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + self.hostname = self.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = self.hostname[0] === '[' && + self.hostname[self.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = self.hostname.split(/\./); + for (i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + self.hostname = validParts.join('.'); + break; + } + } + } + } + + if (self.hostname.length > hostnameMaxLen) { + self.hostname = ''; + } else { + // hostnames are always lower case. + self.hostname = self.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + self.hostname = toASCII(self.hostname); + } + + p = self.port ? ':' + self.port : ''; + var h = self.hostname || ''; + self.host = h + p; + self.href += self.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + self.hostname = self.hostname.substr(1, self.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + self.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + self.search = rest.substr(qm); + self.query = rest.substr(qm + 1); + if (parseQueryString) { + self.query = parse$3(self.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + self.search = ''; + self.query = {}; + } + if (rest) self.pathname = rest; + if (slashedProtocol[lowerProto] && + self.hostname && !self.pathname) { + self.pathname = '/'; + } + + //to support http.request + if (self.pathname || self.search) { + p = self.pathname || ''; + var s = self.search || ''; + self.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + self.href = format$1(self); + return self; + } + + // format a parsed object into a url string + function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (isString(obj)) obj = parse$4({}, obj); + return format$1(obj); + } + + function format$1(self) { + var auth = self.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = self.protocol || '', + pathname = self.pathname || '', + hash = self.hash || '', + host = false, + query = ''; + + if (self.host) { + host = auth + self.host; + } else if (self.hostname) { + host = auth + (self.hostname.indexOf(':') === -1 ? + self.hostname : + '[' + this.hostname + ']'); + if (self.port) { + host += ':' + self.port; + } + } + + if (self.query && + isObject$1(self.query) && + Object.keys(self.query).length) { + query = stringify$1(self.query); + } + + var search = self.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (self.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; + } + + Url.prototype.format = function() { + return format$1(this); + }; + + function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); + } + + Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); + }; + + function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); + } + + Url.prototype.resolveObject = function(relative) { + if (isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + var relPath; + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + relPath = relative.pathname && relative.pathname.split('/') || []; + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + var authInHost; + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!isNull(result.pathname) || !isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!isNull(result.pathname) || !isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + }; + + Url.prototype.parseHost = function() { + return parseHost(this); + }; + + function parseHost(self) { + var host = self.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + self.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) self.hostname = host; + } + + var url$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + parse: urlParse, + resolve: urlResolve, + resolveObject: urlResolveObject, + format: urlFormat, + 'default': url, + Url: Url + }); + + var _import = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = import_; + + function import_(filepath) { + return import(filepath); + } + }); + + unwrapExports(_import); + + var require$$1$1 = getCjsExportFromNamespace(url$1); + + var moduleTypes = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = loadCjsOrMjsDefault; + + + + function _path() { + const data = _interopRequireDefault(require$$1); + + _path = function () { + return data; + }; + + return data; + } + + function _url() { + const data = require$$1$1; + + _url = function () { + return data; + }; + + return data; + } + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + + function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + + let import_; + + try { + import_ = _import.default; + } catch (_unused) {} + + function* loadCjsOrMjsDefault(filepath, asyncError) { + switch (guessJSModuleType(filepath)) { + case "cjs": + return loadCjsDefault(); + + case "unknown": + try { + return loadCjsDefault(filepath); + } catch (e) { + if (e.code !== "ERR_REQUIRE_ESM") throw e; + } + + case "mjs": + if (yield* (0, async.isAsync)()) { + return yield* (0, async.waitFor)(loadMjsDefault(filepath)); + } + + throw new Error(asyncError); + } + } + + function guessJSModuleType(filename) { + switch (_path().default.extname(filename)) { + case ".cjs": + return "cjs"; + + case ".mjs": + return "mjs"; + + default: + return "unknown"; + } + } + + function loadCjsDefault(filepath) { + const module = commonjsRequire(); + + return (module == null ? void 0 : module.__esModule) ? module.default || undefined : module; + } + + function loadMjsDefault(_x) { + return _loadMjsDefault.apply(this, arguments); + } + + function _loadMjsDefault() { + _loadMjsDefault = _asyncToGenerator(function* (filepath) { + if (!import_) { + throw new Error("Internal error: Native ECMAScript modules aren't supported" + " by this platform.\n"); + } + + const module = yield import_((0, _url().pathToFileURL)(filepath)); + return module.default; + }); + return _loadMjsDefault.apply(this, arguments); + } + }); + + unwrapExports(moduleTypes); + + /** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; + } + + var _arrayMap = arrayMap; + + /** Used as references for various `Number` constants. */ + var INFINITY$1 = 1 / 0; + + /** Used to convert symbols to primitives and strings. */ + var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined, + symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined; + + /** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray_1(value)) { + // Recursively convert values (susceptible to call stack limits). + return _arrayMap(value, baseToString) + ''; + } + if (isSymbol_1(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; + } + + var _baseToString = baseToString; + + /** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + function toString$2(value) { + return value == null ? '' : _baseToString(value); + } + + var toString_1 = toString$2; + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar$1 = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar$1.source); + + /** + * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", + * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https://lodash\.com/\)' + */ + function escapeRegExp(string) { + string = toString_1(string); + return (string && reHasRegExpChar.test(string)) + ? string.replace(reRegExpChar$1, '\\$&') + : string; + } + + var escapeRegExp_1 = escapeRegExp; + + var patternToRegex = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = pathToPattern; + + function _path() { + const data = _interopRequireDefault(require$$1); + + _path = function () { + return data; + }; + + return data; + } + + function _escapeRegExp() { + const data = _interopRequireDefault(escapeRegExp_1); + + _escapeRegExp = function () { + return data; + }; + + return data; + } + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + const sep = `\\${_path().default.sep}`; + const endSep = `(?:${sep}|$)`; + const substitution = `[^${sep}]+`; + const starPat = `(?:${substitution}${sep})`; + const starPatLast = `(?:${substitution}${endSep})`; + const starStarPat = `${starPat}*?`; + const starStarPatLast = `${starPat}*?${starPatLast}?`; + + function pathToPattern(pattern, dirname) { + const parts = _path().default.resolve(dirname, pattern).split(_path().default.sep); + + return new RegExp(["^", ...parts.map((part, i) => { + const last = i === parts.length - 1; + if (part === "**") return last ? starStarPatLast : starStarPat; + if (part === "*") return last ? starPatLast : starPat; + + if (part.indexOf("*.") === 0) { + return substitution + (0, _escapeRegExp().default)(part.slice(1)) + (last ? endSep : sep); + } + + return (0, _escapeRegExp().default)(part) + (last ? endSep : sep); + })].join("")); + } + }); + + unwrapExports(patternToRegex); + + var caller = function () { + // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi + var origPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = function (_, stack) { return stack; }; + var stack = (new Error()).stack; + Error.prepareStackTrace = origPrepareStackTrace; + return stack[2].getFileName(); + }; + + var pathParse = createCommonjsModule(function (module) { + + var isWindows = process.platform === 'win32'; + + // Regex to split a windows path into three parts: [*, device, slash, + // tail] windows-only + var splitDeviceRe = + /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; + + // Regex to split the tail part of the above into [*, dir, basename, ext] + var splitTailRe = + /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/; + + var win32 = {}; + + // Function to split a filename into [root, dir, basename, ext] + function win32SplitPath(filename) { + // Separate device+slash from tail + var result = splitDeviceRe.exec(filename), + device = (result[1] || '') + (result[2] || ''), + tail = result[3] || ''; + // Split the tail into dir, basename and extension + var result2 = splitTailRe.exec(tail), + dir = result2[1], + basename = result2[2], + ext = result2[3]; + return [device, dir, basename, ext]; + } + + win32.parse = function(pathString) { + if (typeof pathString !== 'string') { + throw new TypeError( + "Parameter 'pathString' must be a string, not " + typeof pathString + ); + } + var allParts = win32SplitPath(pathString); + if (!allParts || allParts.length !== 4) { + throw new TypeError("Invalid path '" + pathString + "'"); + } + return { + root: allParts[0], + dir: allParts[0] + allParts[1].slice(0, -1), + base: allParts[2], + ext: allParts[3], + name: allParts[2].slice(0, allParts[2].length - allParts[3].length) + }; + }; + + + + // Split a filename into [root, dir, basename, ext], unix version + // 'root' is just a slash, or nothing. + var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; + var posix = {}; + + + function posixSplitPath(filename) { + return splitPathRe.exec(filename).slice(1); + } + + + posix.parse = function(pathString) { + if (typeof pathString !== 'string') { + throw new TypeError( + "Parameter 'pathString' must be a string, not " + typeof pathString + ); + } + var allParts = posixSplitPath(pathString); + if (!allParts || allParts.length !== 4) { + throw new TypeError("Invalid path '" + pathString + "'"); + } + allParts[1] = allParts[1] || ''; + allParts[2] = allParts[2] || ''; + allParts[3] = allParts[3] || ''; + + return { + root: allParts[0], + dir: allParts[0] + allParts[1].slice(0, -1), + base: allParts[2], + ext: allParts[3], + name: allParts[2].slice(0, allParts[2].length - allParts[3].length) + }; + }; + + + if (isWindows) + module.exports = win32.parse; + else /* posix */ + module.exports = posix.parse; + + module.exports.posix = posix.parse; + module.exports.win32 = win32.parse; + }); + var pathParse_1 = pathParse.posix; + var pathParse_2 = pathParse.win32; + + var parse$5 = require$$1.parse || pathParse; + + var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) { + var prefix = '/'; + if ((/^([A-Za-z]:)/).test(absoluteStart)) { + prefix = ''; + } else if ((/^\\\\/).test(absoluteStart)) { + prefix = '\\\\'; + } + + var paths = [absoluteStart]; + var parsed = parse$5(absoluteStart); + while (parsed.dir !== paths[paths.length - 1]) { + paths.push(parsed.dir); + parsed = parse$5(parsed.dir); + } + + return paths.reduce(function (dirs, aPath) { + return dirs.concat(modules.map(function (moduleDir) { + return require$$1.resolve(prefix, aPath, moduleDir); + })); + }, []); + }; + + var nodeModulesPaths = function nodeModulesPaths(start, opts, request) { + var modules = opts && opts.moduleDirectory + ? [].concat(opts.moduleDirectory) + : ['node_modules']; + + if (opts && typeof opts.paths === 'function') { + return opts.paths( + request, + start, + function () { return getNodeModulesDirs(start, modules); }, + opts + ); + } + + var dirs = getNodeModulesDirs(start, modules); + return opts && opts.paths ? dirs.concat(opts.paths) : dirs; + }; + + var normalizeOptions = function (x, opts) { + /** + * This file is purposefully a passthrough. It's expected that third-party + * environments will override it at runtime in order to inject special logic + * into `resolve` (by manipulating the options). One such example is the PnP + * code path in Yarn. + */ + + return opts || {}; + }; + + /* eslint no-invalid-this: 1 */ + + var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; + var slice = Array.prototype.slice; + var toStr = Object.prototype.toString; + var funcType = '[object Function]'; + + var implementation = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.call(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slice.call(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + args.concat(slice.call(arguments)) + ); + if (Object(result) === result) { + return result; + } + return this; + } else { + return target.apply( + that, + args.concat(slice.call(arguments)) + ); + } + }; + + var boundLength = Math.max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs.push('$' + i); + } + + bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; + }; + + var functionBind = Function.prototype.bind || implementation; + + var src$1 = functionBind.call(Function.call, Object.prototype.hasOwnProperty); + + var assert$1 = true; + var async_hooks = ">= 8"; + var buffer_ieee754 = "< 0.9.7"; + var buffer$2 = true; + var child_process = true; + var cluster = true; + var console$1 = true; + var constants$1 = true; + var crypto = true; + var _debug_agent = ">= 1 && < 8"; + var _debugger = "< 8"; + var dgram = true; + var diagnostics_channel = ">= 15.1"; + var dns = true; + var domain = ">= 0.7.12"; + var events = true; + var freelist = "< 6"; + var fs$1 = true; + var _http_agent = ">= 0.11.1"; + var _http_client = ">= 0.11.1"; + var _http_common = ">= 0.11.1"; + var _http_incoming = ">= 0.11.1"; + var _http_outgoing = ">= 0.11.1"; + var _http_server = ">= 0.11.1"; + var http = true; + var http2 = ">= 8.8"; + var https = true; + var inspector = ">= 8.0.0"; + var _linklist = "< 8"; + var module = true; + var net = true; + var os$3 = true; + var path$1 = true; + var perf_hooks = ">= 8.5"; + var process$1 = ">= 1"; + var punycode = true; + var querystring = true; + var readline = true; + var repl = true; + var smalloc = ">= 0.11.5 && < 3"; + var _stream_duplex = ">= 0.9.4"; + var _stream_transform = ">= 0.9.4"; + var _stream_wrap = ">= 1.4.1"; + var _stream_passthrough = ">= 0.9.4"; + var _stream_readable = ">= 0.9.4"; + var _stream_writable = ">= 0.9.4"; + var stream = true; + var string_decoder = true; + var sys = [ + ">= 0.6 && < 0.7", + ">= 0.8" + ]; + var timers = true; + var _tls_common = ">= 0.11.13"; + var _tls_legacy = ">= 0.11.3 && < 10"; + var _tls_wrap = ">= 0.11.3"; + var tls = true; + var trace_events = ">= 10"; + var tty$3 = true; + var url$2 = true; + var util$6 = true; + var v8 = ">= 1"; + var vm = true; + var wasi = ">= 13.4 && < 13.5"; + var worker_threads = ">= 11.7"; + var zlib = true; + var core$1 = { + assert: assert$1, + "assert/strict": ">= 15", + async_hooks: async_hooks, + buffer_ieee754: buffer_ieee754, + buffer: buffer$2, + child_process: child_process, + cluster: cluster, + console: console$1, + constants: constants$1, + crypto: crypto, + _debug_agent: _debug_agent, + _debugger: _debugger, + dgram: dgram, + diagnostics_channel: diagnostics_channel, + dns: dns, + "dns/promises": ">= 15", + domain: domain, + events: events, + freelist: freelist, + fs: fs$1, + "fs/promises": [ + ">= 10 && < 10.1", + ">= 14" + ], + _http_agent: _http_agent, + _http_client: _http_client, + _http_common: _http_common, + _http_incoming: _http_incoming, + _http_outgoing: _http_outgoing, + _http_server: _http_server, + http: http, + http2: http2, + https: https, + inspector: inspector, + _linklist: _linklist, + module: module, + net: net, + "node-inspect/lib/_inspect": ">= 7.6.0 && < 12", + "node-inspect/lib/internal/inspect_client": ">= 7.6.0 && < 12", + "node-inspect/lib/internal/inspect_repl": ">= 7.6.0 && < 12", + os: os$3, + path: path$1, + perf_hooks: perf_hooks, + process: process$1, + punycode: punycode, + querystring: querystring, + readline: readline, + repl: repl, + smalloc: smalloc, + _stream_duplex: _stream_duplex, + _stream_transform: _stream_transform, + _stream_wrap: _stream_wrap, + _stream_passthrough: _stream_passthrough, + _stream_readable: _stream_readable, + _stream_writable: _stream_writable, + stream: stream, + "stream/promises": ">= 15", + string_decoder: string_decoder, + sys: sys, + timers: timers, + "timers/promises": ">= 15", + _tls_common: _tls_common, + _tls_legacy: _tls_legacy, + _tls_wrap: _tls_wrap, + tls: tls, + trace_events: trace_events, + tty: tty$3, + url: url$2, + util: util$6, + "v8/tools/arguments": ">= 10 && < 12", + "v8/tools/codemap": [ + ">= 4.4.0 && < 5", + ">= 5.2.0 && < 12" + ], + "v8/tools/consarray": [ + ">= 4.4.0 && < 5", + ">= 5.2.0 && < 12" + ], + "v8/tools/csvparser": [ + ">= 4.4.0 && < 5", + ">= 5.2.0 && < 12" + ], + "v8/tools/logreader": [ + ">= 4.4.0 && < 5", + ">= 5.2.0 && < 12" + ], + "v8/tools/profile_view": [ + ">= 4.4.0 && < 5", + ">= 5.2.0 && < 12" + ], + "v8/tools/splaytree": [ + ">= 4.4.0 && < 5", + ">= 5.2.0 && < 12" + ], + v8: v8, + vm: vm, + wasi: wasi, + worker_threads: worker_threads, + zlib: zlib + }; + + var core$2 = /*#__PURE__*/Object.freeze({ + __proto__: null, + assert: assert$1, + async_hooks: async_hooks, + buffer_ieee754: buffer_ieee754, + buffer: buffer$2, + child_process: child_process, + cluster: cluster, + console: console$1, + constants: constants$1, + crypto: crypto, + _debug_agent: _debug_agent, + _debugger: _debugger, + dgram: dgram, + diagnostics_channel: diagnostics_channel, + dns: dns, + domain: domain, + events: events, + freelist: freelist, + fs: fs$1, + _http_agent: _http_agent, + _http_client: _http_client, + _http_common: _http_common, + _http_incoming: _http_incoming, + _http_outgoing: _http_outgoing, + _http_server: _http_server, + http: http, + http2: http2, + https: https, + inspector: inspector, + _linklist: _linklist, + module: module, + net: net, + os: os$3, + path: path$1, + perf_hooks: perf_hooks, + process: process$1, + punycode: punycode, + querystring: querystring, + readline: readline, + repl: repl, + smalloc: smalloc, + _stream_duplex: _stream_duplex, + _stream_transform: _stream_transform, + _stream_wrap: _stream_wrap, + _stream_passthrough: _stream_passthrough, + _stream_readable: _stream_readable, + _stream_writable: _stream_writable, + stream: stream, + string_decoder: string_decoder, + sys: sys, + timers: timers, + _tls_common: _tls_common, + _tls_legacy: _tls_legacy, + _tls_wrap: _tls_wrap, + tls: tls, + trace_events: trace_events, + tty: tty$3, + url: url$2, + util: util$6, + v8: v8, + vm: vm, + wasi: wasi, + worker_threads: worker_threads, + zlib: zlib, + 'default': core$1 + }); + + var data = getCjsExportFromNamespace(core$2); + + function specifierIncluded(current, specifier) { + var nodeParts = current.split('.'); + var parts = specifier.split(' '); + var op = parts.length > 1 ? parts[0] : '='; + var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); + + for (var i = 0; i < 3; ++i) { + var cur = parseInt(nodeParts[i] || 0, 10); + var ver = parseInt(versionParts[i] || 0, 10); + if (cur === ver) { + continue; // eslint-disable-line no-restricted-syntax, no-continue + } + if (op === '<') { + return cur < ver; + } + if (op === '>=') { + return cur >= ver; + } + return false; + } + return op === '>='; + } + + function matchesRange(current, range) { + var specifiers = range.split(/ ?&& ?/); + if (specifiers.length === 0) { + return false; + } + for (var i = 0; i < specifiers.length; ++i) { + if (!specifierIncluded(current, specifiers[i])) { + return false; + } + } + return true; + } + + function versionIncluded(nodeVersion, specifierValue) { + if (typeof specifierValue === 'boolean') { + return specifierValue; + } + + var current = typeof nodeVersion === 'undefined' + ? process.versions && process.versions.node && process.versions.node + : nodeVersion; + + if (typeof current !== 'string') { + throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required'); + } + + if (specifierValue && typeof specifierValue === 'object') { + for (var i = 0; i < specifierValue.length; ++i) { + if (matchesRange(current, specifierValue[i])) { + return true; + } + } + return false; + } + return matchesRange(current, specifierValue); + } + + + + var isCoreModule = function isCore(x, nodeVersion) { + return src$1(data, x) && versionIncluded(nodeVersion, data[x]); + }; + + var realpathFS = require$$0$1.realpath && typeof require$$0$1.realpath.native === 'function' ? require$$0$1.realpath.native : require$$0$1.realpath; + + var defaultIsFile = function isFile(file, cb) { + require$$0$1.stat(file, function (err, stat) { + if (!err) { + return cb(null, stat.isFile() || stat.isFIFO()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); + }; + + var defaultIsDir = function isDirectory(dir, cb) { + require$$0$1.stat(dir, function (err, stat) { + if (!err) { + return cb(null, stat.isDirectory()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); + }; + + var defaultRealpath = function realpath(x, cb) { + realpathFS(x, function (realpathErr, realPath) { + if (realpathErr && realpathErr.code !== 'ENOENT') cb(realpathErr); + else cb(null, realpathErr ? x : realPath); + }); + }; + + var maybeRealpath = function maybeRealpath(realpath, x, opts, cb) { + if (opts && opts.preserveSymlinks === false) { + realpath(x, cb); + } else { + cb(null, x); + } + }; + + var getPackageCandidates = function getPackageCandidates(x, start, opts) { + var dirs = nodeModulesPaths(start, opts, x); + for (var i = 0; i < dirs.length; i++) { + dirs[i] = require$$1.join(dirs[i], x); + } + return dirs; + }; + + var async$1 = function resolve(x, options, callback) { + var cb = callback; + var opts = options; + if (typeof options === 'function') { + cb = opts; + opts = {}; + } + if (typeof x !== 'string') { + var err = new TypeError('Path must be a string.'); + return nextTick(function () { + cb(err); + }); + } + + opts = normalizeOptions(x, opts); + + var isFile = opts.isFile || defaultIsFile; + var isDirectory = opts.isDirectory || defaultIsDir; + var readFile = opts.readFile || require$$0$1.readFile; + var realpath = opts.realpath || defaultRealpath; + var packageIterator = opts.packageIterator; + + var extensions = opts.extensions || ['.js']; + var includeCoreModules = opts.includeCoreModules !== false; + var basedir = opts.basedir || require$$1.dirname(caller()); + var parent = opts.filename || basedir; + + opts.paths = opts.paths || []; + + // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory + var absoluteStart = require$$1.resolve(basedir); + + maybeRealpath( + realpath, + absoluteStart, + opts, + function (err, realStart) { + if (err) cb(err); + else init(realStart); + } + ); + + var res; + function init(basedir) { + if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { + res = require$$1.resolve(basedir, x); + if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; + if ((/\/$/).test(x) && res === basedir) { + loadAsDirectory(res, opts.package, onfile); + } else loadAsFile(res, opts.package, onfile); + } else if (includeCoreModules && isCoreModule(x)) { + return cb(null, x); + } else loadNodeModules(x, basedir, function (err, n, pkg) { + if (err) cb(err); + else if (n) { + return maybeRealpath(realpath, n, opts, function (err, realN) { + if (err) { + cb(err); + } else { + cb(null, realN, pkg); + } + }); + } else { + var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + moduleError.code = 'MODULE_NOT_FOUND'; + cb(moduleError); + } + }); + } + + function onfile(err, m, pkg) { + if (err) cb(err); + else if (m) cb(null, m, pkg); + else loadAsDirectory(res, function (err, d, pkg) { + if (err) cb(err); + else if (d) { + maybeRealpath(realpath, d, opts, function (err, realD) { + if (err) { + cb(err); + } else { + cb(null, realD, pkg); + } + }); + } else { + var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + moduleError.code = 'MODULE_NOT_FOUND'; + cb(moduleError); + } + }); + } + + function loadAsFile(x, thePackage, callback) { + var loadAsFilePackage = thePackage; + var cb = callback; + if (typeof loadAsFilePackage === 'function') { + cb = loadAsFilePackage; + loadAsFilePackage = undefined; + } + + var exts = [''].concat(extensions); + load(exts, x, loadAsFilePackage); + + function load(exts, x, loadPackage) { + if (exts.length === 0) return cb(null, undefined, loadPackage); + var file = x + exts[0]; + + var pkg = loadPackage; + if (pkg) onpkg(null, pkg); + else loadpkg(require$$1.dirname(file), onpkg); + + function onpkg(err, pkg_, dir) { + pkg = pkg_; + if (err) return cb(err); + if (dir && pkg && opts.pathFilter) { + var rfile = require$$1.relative(dir, file); + var rel = rfile.slice(0, rfile.length - exts[0].length); + var r = opts.pathFilter(pkg, x, rel); + if (r) return load( + [''].concat(extensions.slice()), + require$$1.resolve(dir, r), + pkg + ); + } + isFile(file, onex); + } + function onex(err, ex) { + if (err) return cb(err); + if (ex) return cb(null, file, pkg); + load(exts.slice(1), x, pkg); + } + } + } + + function loadpkg(dir, cb) { + if (dir === '' || dir === '/') return cb(null); + if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { + return cb(null); + } + if ((/[/\\]node_modules[/\\]*$/).test(dir)) return cb(null); + + maybeRealpath(realpath, dir, opts, function (unwrapErr, pkgdir) { + if (unwrapErr) return loadpkg(require$$1.dirname(dir), cb); + var pkgfile = require$$1.join(pkgdir, 'package.json'); + isFile(pkgfile, function (err, ex) { + // on err, ex is false + if (!ex) return loadpkg(require$$1.dirname(dir), cb); + + readFile(pkgfile, function (err, body) { + if (err) cb(err); + try { var pkg = JSON.parse(body); } catch (jsonErr) {} + + if (pkg && opts.packageFilter) { + pkg = opts.packageFilter(pkg, pkgfile); + } + cb(null, pkg, dir); + }); + }); + }); + } + + function loadAsDirectory(x, loadAsDirectoryPackage, callback) { + var cb = callback; + var fpkg = loadAsDirectoryPackage; + if (typeof fpkg === 'function') { + cb = fpkg; + fpkg = opts.package; + } + + maybeRealpath(realpath, x, opts, function (unwrapErr, pkgdir) { + if (unwrapErr) return cb(unwrapErr); + var pkgfile = require$$1.join(pkgdir, 'package.json'); + isFile(pkgfile, function (err, ex) { + if (err) return cb(err); + if (!ex) return loadAsFile(require$$1.join(x, 'index'), fpkg, cb); + + readFile(pkgfile, function (err, body) { + if (err) return cb(err); + try { + var pkg = JSON.parse(body); + } catch (jsonErr) {} + + if (pkg && opts.packageFilter) { + pkg = opts.packageFilter(pkg, pkgfile); + } + + if (pkg && pkg.main) { + if (typeof pkg.main !== 'string') { + var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); + mainError.code = 'INVALID_PACKAGE_MAIN'; + return cb(mainError); + } + if (pkg.main === '.' || pkg.main === './') { + pkg.main = 'index'; + } + loadAsFile(require$$1.resolve(x, pkg.main), pkg, function (err, m, pkg) { + if (err) return cb(err); + if (m) return cb(null, m, pkg); + if (!pkg) return loadAsFile(require$$1.join(x, 'index'), pkg, cb); + + var dir = require$$1.resolve(x, pkg.main); + loadAsDirectory(dir, pkg, function (err, n, pkg) { + if (err) return cb(err); + if (n) return cb(null, n, pkg); + loadAsFile(require$$1.join(x, 'index'), pkg, cb); + }); + }); + return; + } + + loadAsFile(require$$1.join(x, '/index'), pkg, cb); + }); + }); + }); + } + + function processDirs(cb, dirs) { + if (dirs.length === 0) return cb(null, undefined); + var dir = dirs[0]; + + isDirectory(require$$1.dirname(dir), isdir); + + function isdir(err, isdir) { + if (err) return cb(err); + if (!isdir) return processDirs(cb, dirs.slice(1)); + loadAsFile(dir, opts.package, onfile); + } + + function onfile(err, m, pkg) { + if (err) return cb(err); + if (m) return cb(null, m, pkg); + loadAsDirectory(dir, opts.package, ondir); + } + + function ondir(err, n, pkg) { + if (err) return cb(err); + if (n) return cb(null, n, pkg); + processDirs(cb, dirs.slice(1)); + } + } + function loadNodeModules(x, start, cb) { + var thunk = function () { return getPackageCandidates(x, start, opts); }; + processDirs( + cb, + packageIterator ? packageIterator(x, start, thunk, opts) : thunk() + ); + } + }; + + var assert$2 = true; + var async_hooks$1 = ">= 8"; + var buffer_ieee754$1 = "< 0.9.7"; + var buffer$3 = true; + var child_process$1 = true; + var cluster$1 = true; + var console$2 = true; + var constants$2 = true; + var crypto$1 = true; + var _debug_agent$1 = ">= 1 && < 8"; + var _debugger$1 = "< 8"; + var dgram$1 = true; + var diagnostics_channel$1 = ">= 15.1"; + var dns$1 = true; + var domain$1 = ">= 0.7.12"; + var events$1 = true; + var freelist$1 = "< 6"; + var fs$2 = true; + var _http_agent$1 = ">= 0.11.1"; + var _http_client$1 = ">= 0.11.1"; + var _http_common$1 = ">= 0.11.1"; + var _http_incoming$1 = ">= 0.11.1"; + var _http_outgoing$1 = ">= 0.11.1"; + var _http_server$1 = ">= 0.11.1"; + var http$1 = true; + var http2$1 = ">= 8.8"; + var https$1 = true; + var inspector$1 = ">= 8.0.0"; + var _linklist$1 = "< 8"; + var module$1 = true; + var net$1 = true; + var os$4 = true; + var path$2 = true; + var perf_hooks$1 = ">= 8.5"; + var process$2 = ">= 1"; + var punycode$1 = true; + var querystring$1 = true; + var readline$1 = true; + var repl$1 = true; + var smalloc$1 = ">= 0.11.5 && < 3"; + var _stream_duplex$1 = ">= 0.9.4"; + var _stream_transform$1 = ">= 0.9.4"; + var _stream_wrap$1 = ">= 1.4.1"; + var _stream_passthrough$1 = ">= 0.9.4"; + var _stream_readable$1 = ">= 0.9.4"; + var _stream_writable$1 = ">= 0.9.4"; + var stream$1 = true; + var string_decoder$1 = true; + var sys$1 = [ + ">= 0.6 && < 0.7", + ">= 0.8" + ]; + var timers$1 = true; + var _tls_common$1 = ">= 0.11.13"; + var _tls_legacy$1 = ">= 0.11.3 && < 10"; + var _tls_wrap$1 = ">= 0.11.3"; + var tls$1 = true; + var trace_events$1 = ">= 10"; + var tty$4 = true; + var url$3 = true; + var util$7 = true; + var v8$1 = ">= 1"; + var vm$1 = true; + var wasi$1 = ">= 13.4 && < 13.5"; + var worker_threads$1 = ">= 11.7"; + var zlib$1 = true; + var core$3 = { + assert: assert$2, + "assert/strict": ">= 15", + async_hooks: async_hooks$1, + buffer_ieee754: buffer_ieee754$1, + buffer: buffer$3, + child_process: child_process$1, + cluster: cluster$1, + console: console$2, + constants: constants$2, + crypto: crypto$1, + _debug_agent: _debug_agent$1, + _debugger: _debugger$1, + dgram: dgram$1, + diagnostics_channel: diagnostics_channel$1, + dns: dns$1, + "dns/promises": ">= 15", + domain: domain$1, + events: events$1, + freelist: freelist$1, + fs: fs$2, + "fs/promises": [ + ">= 10 && < 10.1", + ">= 14" + ], + _http_agent: _http_agent$1, + _http_client: _http_client$1, + _http_common: _http_common$1, + _http_incoming: _http_incoming$1, + _http_outgoing: _http_outgoing$1, + _http_server: _http_server$1, + http: http$1, + http2: http2$1, + https: https$1, + inspector: inspector$1, + _linklist: _linklist$1, + module: module$1, + net: net$1, + "node-inspect/lib/_inspect": ">= 7.6.0 && < 12", + "node-inspect/lib/internal/inspect_client": ">= 7.6.0 && < 12", + "node-inspect/lib/internal/inspect_repl": ">= 7.6.0 && < 12", + os: os$4, + path: path$2, + perf_hooks: perf_hooks$1, + process: process$2, + punycode: punycode$1, + querystring: querystring$1, + readline: readline$1, + repl: repl$1, + smalloc: smalloc$1, + _stream_duplex: _stream_duplex$1, + _stream_transform: _stream_transform$1, + _stream_wrap: _stream_wrap$1, + _stream_passthrough: _stream_passthrough$1, + _stream_readable: _stream_readable$1, + _stream_writable: _stream_writable$1, + stream: stream$1, + "stream/promises": ">= 15", + string_decoder: string_decoder$1, + sys: sys$1, + timers: timers$1, + "timers/promises": ">= 15", + _tls_common: _tls_common$1, + _tls_legacy: _tls_legacy$1, + _tls_wrap: _tls_wrap$1, + tls: tls$1, + trace_events: trace_events$1, + tty: tty$4, + url: url$3, + util: util$7, + "v8/tools/arguments": ">= 10 && < 12", + "v8/tools/codemap": [ + ">= 4.4.0 && < 5", + ">= 5.2.0 && < 12" + ], + "v8/tools/consarray": [ + ">= 4.4.0 && < 5", + ">= 5.2.0 && < 12" + ], + "v8/tools/csvparser": [ + ">= 4.4.0 && < 5", + ">= 5.2.0 && < 12" + ], + "v8/tools/logreader": [ + ">= 4.4.0 && < 5", + ">= 5.2.0 && < 12" + ], + "v8/tools/profile_view": [ + ">= 4.4.0 && < 5", + ">= 5.2.0 && < 12" + ], + "v8/tools/splaytree": [ + ">= 4.4.0 && < 5", + ">= 5.2.0 && < 12" + ], + v8: v8$1, + vm: vm$1, + wasi: wasi$1, + worker_threads: worker_threads$1, + zlib: zlib$1 + }; + + var core$4 = /*#__PURE__*/Object.freeze({ + __proto__: null, + assert: assert$2, + async_hooks: async_hooks$1, + buffer_ieee754: buffer_ieee754$1, + buffer: buffer$3, + child_process: child_process$1, + cluster: cluster$1, + console: console$2, + constants: constants$2, + crypto: crypto$1, + _debug_agent: _debug_agent$1, + _debugger: _debugger$1, + dgram: dgram$1, + diagnostics_channel: diagnostics_channel$1, + dns: dns$1, + domain: domain$1, + events: events$1, + freelist: freelist$1, + fs: fs$2, + _http_agent: _http_agent$1, + _http_client: _http_client$1, + _http_common: _http_common$1, + _http_incoming: _http_incoming$1, + _http_outgoing: _http_outgoing$1, + _http_server: _http_server$1, + http: http$1, + http2: http2$1, + https: https$1, + inspector: inspector$1, + _linklist: _linklist$1, + module: module$1, + net: net$1, + os: os$4, + path: path$2, + perf_hooks: perf_hooks$1, + process: process$2, + punycode: punycode$1, + querystring: querystring$1, + readline: readline$1, + repl: repl$1, + smalloc: smalloc$1, + _stream_duplex: _stream_duplex$1, + _stream_transform: _stream_transform$1, + _stream_wrap: _stream_wrap$1, + _stream_passthrough: _stream_passthrough$1, + _stream_readable: _stream_readable$1, + _stream_writable: _stream_writable$1, + stream: stream$1, + string_decoder: string_decoder$1, + sys: sys$1, + timers: timers$1, + _tls_common: _tls_common$1, + _tls_legacy: _tls_legacy$1, + _tls_wrap: _tls_wrap$1, + tls: tls$1, + trace_events: trace_events$1, + tty: tty$4, + url: url$3, + util: util$7, + v8: v8$1, + vm: vm$1, + wasi: wasi$1, + worker_threads: worker_threads$1, + zlib: zlib$1, + 'default': core$3 + }); + + var data$1 = getCjsExportFromNamespace(core$4); + + var current = (process.versions && process.versions.node && process.versions.node.split('.')) || []; + + function specifierIncluded$1(specifier) { + var parts = specifier.split(' '); + var op = parts.length > 1 ? parts[0] : '='; + var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); + + for (var i = 0; i < 3; ++i) { + var cur = parseInt(current[i] || 0, 10); + var ver = parseInt(versionParts[i] || 0, 10); + if (cur === ver) { + continue; // eslint-disable-line no-restricted-syntax, no-continue + } + if (op === '<') { + return cur < ver; + } else if (op === '>=') { + return cur >= ver; + } else { + return false; + } + } + return op === '>='; + } + + function matchesRange$1(range) { + var specifiers = range.split(/ ?&& ?/); + if (specifiers.length === 0) { return false; } + for (var i = 0; i < specifiers.length; ++i) { + if (!specifierIncluded$1(specifiers[i])) { return false; } + } + return true; + } + + function versionIncluded$1(specifierValue) { + if (typeof specifierValue === 'boolean') { return specifierValue; } + if (specifierValue && typeof specifierValue === 'object') { + for (var i = 0; i < specifierValue.length; ++i) { + if (matchesRange$1(specifierValue[i])) { return true; } + } + return false; + } + return matchesRange$1(specifierValue); + } + + + + var core$5 = {}; + for (var mod in data$1) { // eslint-disable-line no-restricted-syntax + if (Object.prototype.hasOwnProperty.call(data$1, mod)) { + core$5[mod] = versionIncluded$1(data$1[mod]); + } + } + var core_1$1 = core$5; + + var isCore = function isCore(x) { + return isCoreModule(x); + }; + + var realpathFS$1 = require$$0$1.realpathSync && typeof require$$0$1.realpathSync.native === 'function' ? require$$0$1.realpathSync.native : require$$0$1.realpathSync; + + var defaultIsFile$1 = function isFile(file) { + try { + var stat = require$$0$1.statSync(file); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; + } + return stat.isFile() || stat.isFIFO(); + }; + + var defaultIsDir$1 = function isDirectory(dir) { + try { + var stat = require$$0$1.statSync(dir); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; + } + return stat.isDirectory(); + }; + + var defaultRealpathSync = function realpathSync(x) { + try { + return realpathFS$1(x); + } catch (realpathErr) { + if (realpathErr.code !== 'ENOENT') { + throw realpathErr; + } + } + return x; + }; + + var maybeRealpathSync = function maybeRealpathSync(realpathSync, x, opts) { + if (opts && opts.preserveSymlinks === false) { + return realpathSync(x); + } + return x; + }; + + var getPackageCandidates$1 = function getPackageCandidates(x, start, opts) { + var dirs = nodeModulesPaths(start, opts, x); + for (var i = 0; i < dirs.length; i++) { + dirs[i] = require$$1.join(dirs[i], x); + } + return dirs; + }; + + var sync = function resolveSync(x, options) { + if (typeof x !== 'string') { + throw new TypeError('Path must be a string.'); + } + var opts = normalizeOptions(x, options); + + var isFile = opts.isFile || defaultIsFile$1; + var readFileSync = opts.readFileSync || require$$0$1.readFileSync; + var isDirectory = opts.isDirectory || defaultIsDir$1; + var realpathSync = opts.realpathSync || defaultRealpathSync; + var packageIterator = opts.packageIterator; + + var extensions = opts.extensions || ['.js']; + var includeCoreModules = opts.includeCoreModules !== false; + var basedir = opts.basedir || require$$1.dirname(caller()); + var parent = opts.filename || basedir; + + opts.paths = opts.paths || []; + + // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory + var absoluteStart = maybeRealpathSync(realpathSync, require$$1.resolve(basedir), opts); + + if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { + var res = require$$1.resolve(absoluteStart, x); + if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; + var m = loadAsFileSync(res) || loadAsDirectorySync(res); + if (m) return maybeRealpathSync(realpathSync, m, opts); + } else if (includeCoreModules && isCoreModule(x)) { + return x; + } else { + var n = loadNodeModulesSync(x, absoluteStart); + if (n) return maybeRealpathSync(realpathSync, n, opts); + } + + var err = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + err.code = 'MODULE_NOT_FOUND'; + throw err; + + function loadAsFileSync(x) { + var pkg = loadpkg(require$$1.dirname(x)); + + if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) { + var rfile = require$$1.relative(pkg.dir, x); + var r = opts.pathFilter(pkg.pkg, x, rfile); + if (r) { + x = require$$1.resolve(pkg.dir, r); // eslint-disable-line no-param-reassign + } + } + + if (isFile(x)) { + return x; + } + + for (var i = 0; i < extensions.length; i++) { + var file = x + extensions[i]; + if (isFile(file)) { + return file; + } + } + } + + function loadpkg(dir) { + if (dir === '' || dir === '/') return; + if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { + return; + } + if ((/[/\\]node_modules[/\\]*$/).test(dir)) return; + + var pkgfile = require$$1.join(maybeRealpathSync(realpathSync, dir, opts), 'package.json'); + + if (!isFile(pkgfile)) { + return loadpkg(require$$1.dirname(dir)); + } + + var body = readFileSync(pkgfile); + + try { + var pkg = JSON.parse(body); + } catch (jsonErr) {} + + if (pkg && opts.packageFilter) { + // v2 will pass pkgfile + pkg = opts.packageFilter(pkg, /*pkgfile,*/ dir); // eslint-disable-line spaced-comment + } + + return { pkg: pkg, dir: dir }; + } + + function loadAsDirectorySync(x) { + var pkgfile = require$$1.join(maybeRealpathSync(realpathSync, x, opts), '/package.json'); + if (isFile(pkgfile)) { + try { + var body = readFileSync(pkgfile, 'UTF8'); + var pkg = JSON.parse(body); + } catch (e) {} + + if (pkg && opts.packageFilter) { + // v2 will pass pkgfile + pkg = opts.packageFilter(pkg, /*pkgfile,*/ x); // eslint-disable-line spaced-comment + } + + if (pkg && pkg.main) { + if (typeof pkg.main !== 'string') { + var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); + mainError.code = 'INVALID_PACKAGE_MAIN'; + throw mainError; + } + if (pkg.main === '.' || pkg.main === './') { + pkg.main = 'index'; + } + try { + var m = loadAsFileSync(require$$1.resolve(x, pkg.main)); + if (m) return m; + var n = loadAsDirectorySync(require$$1.resolve(x, pkg.main)); + if (n) return n; + } catch (e) {} + } + } + + return loadAsFileSync(require$$1.join(x, '/index')); + } + + function loadNodeModulesSync(x, start) { + var thunk = function () { return getPackageCandidates$1(x, start, opts); }; + var dirs = packageIterator ? packageIterator(x, start, thunk, opts) : thunk(); + + for (var i = 0; i < dirs.length; i++) { + var dir = dirs[i]; + if (isDirectory(require$$1.dirname(dir))) { + var m = loadAsFileSync(dir); + if (m) return m; + var n = loadAsDirectorySync(dir); + if (n) return n; + } + } + } + }; + + async$1.core = core_1$1; + async$1.isCore = isCore; + async$1.sync = sync; + + var resolve$1 = async$1; + + var resolve$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = void 0; + + function _resolve() { + const data = _interopRequireDefault(resolve$1); + + _resolve = function () { + return data; + }; + + return data; + } + + function _gensync() { + const data = _interopRequireDefault(gensync); + + _gensync = function () { + return data; + }; + + return data; + } + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + var _default = (0, _gensync().default)({ + sync: _resolve().default.sync, + errback: _resolve().default + }); + + exports.default = _default; + }); + + unwrapExports(resolve$2); + + var require$$2 = getCjsExportFromNamespace(dist); + + var configuration = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.findConfigUpwards = findConfigUpwards; + exports.findRelativeConfig = findRelativeConfig; + exports.findRootConfig = findRootConfig; + exports.loadConfig = loadConfig; + exports.resolveShowConfigPath = resolveShowConfigPath; + exports.ROOT_CONFIG_FILENAMES = void 0; + + function _debug() { + const data = _interopRequireDefault(src); + + _debug = function () { + return data; + }; + + return data; + } + + function _path() { + const data = _interopRequireDefault(require$$1); + + _path = function () { + return data; + }; + + return data; + } + + function _json() { + const data = _interopRequireDefault(require$$2); + + _json = function () { + return data; + }; + + return data; + } + + function _gensync() { + const data = _interopRequireDefault(gensync); + + _gensync = function () { + return data; + }; + + return data; + } + + + + var _configApi = _interopRequireDefault(configApi); + + + + var _moduleTypes = _interopRequireDefault(moduleTypes); + + var _patternToRegex = _interopRequireDefault(patternToRegex); + + var fs$1 = _interopRequireWildcard(fs); + + var _resolve = _interopRequireDefault(resolve$2); + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + const debug = (0, _debug().default)("babel:config:loading:files:configuration"); + const ROOT_CONFIG_FILENAMES = ["babel.config.js", "babel.config.cjs", "babel.config.mjs", "babel.config.json"]; + exports.ROOT_CONFIG_FILENAMES = ROOT_CONFIG_FILENAMES; + const RELATIVE_CONFIG_FILENAMES = [".babelrc", ".babelrc.js", ".babelrc.cjs", ".babelrc.mjs", ".babelrc.json"]; + const BABELIGNORE_FILENAME = ".babelignore"; + + function* findConfigUpwards(rootDir) { + let dirname = rootDir; + + while (true) { + for (const filename of ROOT_CONFIG_FILENAMES) { + if (yield* fs$1.exists(_path().default.join(dirname, filename))) { + return dirname; + } + } + + const nextDir = _path().default.dirname(dirname); + + if (dirname === nextDir) break; + dirname = nextDir; + } + + return null; + } + + function* findRelativeConfig(packageData, envName, caller) { + let config = null; + let ignore = null; + + const dirname = _path().default.dirname(packageData.filepath); + + for (const loc of packageData.directories) { + if (!config) { + var _packageData$pkg; + + config = yield* loadOneConfig(RELATIVE_CONFIG_FILENAMES, loc, envName, caller, ((_packageData$pkg = packageData.pkg) == null ? void 0 : _packageData$pkg.dirname) === loc ? packageToBabelConfig(packageData.pkg) : null); + } + + if (!ignore) { + const ignoreLoc = _path().default.join(loc, BABELIGNORE_FILENAME); + + ignore = yield* readIgnoreConfig(ignoreLoc); + + if (ignore) { + debug("Found ignore %o from %o.", ignore.filepath, dirname); + } + } + } + + return { + config, + ignore + }; + } + + function findRootConfig(dirname, envName, caller) { + return loadOneConfig(ROOT_CONFIG_FILENAMES, dirname, envName, caller); + } + + function* loadOneConfig(names, dirname, envName, caller, previousConfig = null) { + const configs = yield* _gensync().default.all(names.map(filename => readConfig(_path().default.join(dirname, filename), envName, caller))); + const config = configs.reduce((previousConfig, config) => { + if (config && previousConfig) { + throw new Error(`Multiple configuration files found. Please remove one:\n` + ` - ${_path().default.basename(previousConfig.filepath)}\n` + ` - ${config.filepath}\n` + `from ${dirname}`); + } + + return config || previousConfig; + }, previousConfig); + + if (config) { + debug("Found configuration %o from %o.", config.filepath, dirname); + } + + return config; + } + + function* loadConfig(name, dirname, envName, caller) { + const filepath = yield* (0, _resolve.default)(name, { + basedir: dirname + }); + const conf = yield* readConfig(filepath, envName, caller); + + if (!conf) { + throw new Error(`Config file ${filepath} contains no configuration data`); + } + + debug("Loaded config %o from %o.", name, dirname); + return conf; + } + + function readConfig(filepath, envName, caller) { + const ext = _path().default.extname(filepath); + + return ext === ".js" || ext === ".cjs" || ext === ".mjs" ? readConfigJS(filepath, { + envName, + caller + }) : readConfigJSON5(filepath); + } + + const LOADING_CONFIGS = new Set(); + const readConfigJS = (0, caching.makeStrongCache)(function* readConfigJS(filepath, cache) { + if (!fs$1.exists.sync(filepath)) { + cache.forever(); + return null; + } + + if (LOADING_CONFIGS.has(filepath)) { + cache.never(); + debug("Auto-ignoring usage of config %o.", filepath); + return { + filepath, + dirname: _path().default.dirname(filepath), + options: {} + }; + } + + let options; + + try { + LOADING_CONFIGS.add(filepath); + options = yield* (0, _moduleTypes.default)(filepath, "You appear to be using a native ECMAScript module configuration " + "file, which is only supported when running Babel asynchronously."); + } catch (err) { + err.message = `${filepath}: Error while loading config - ${err.message}`; + throw err; + } finally { + LOADING_CONFIGS.delete(filepath); + } + + let assertCache = false; + + if (typeof options === "function") { + yield* []; + options = options((0, _configApi.default)(cache)); + assertCache = true; + } + + if (!options || typeof options !== "object" || Array.isArray(options)) { + throw new Error(`${filepath}: Configuration should be an exported JavaScript object.`); + } + + if (typeof options.then === "function") { + throw new Error(`You appear to be using an async configuration, ` + `which your current version of Babel does not support. ` + `We may add support for this in the future, ` + `but if you're on the most recent version of @babel/core and still ` + `seeing this error, then you'll need to synchronously return your config.`); + } + + if (assertCache && !cache.configured()) throwConfigError(); + return { + filepath, + dirname: _path().default.dirname(filepath), + options + }; + }); + const packageToBabelConfig = (0, caching.makeWeakCacheSync)(file => { + const babel = file.options["babel"]; + if (typeof babel === "undefined") return null; + + if (typeof babel !== "object" || Array.isArray(babel) || babel === null) { + throw new Error(`${file.filepath}: .babel property must be an object`); + } + + return { + filepath: file.filepath, + dirname: file.dirname, + options: babel + }; + }); + const readConfigJSON5 = (0, utils$1.makeStaticFileCache)((filepath, content) => { + let options; + + try { + options = _json().default.parse(content); + } catch (err) { + err.message = `${filepath}: Error while parsing config - ${err.message}`; + throw err; + } + + if (!options) throw new Error(`${filepath}: No config detected`); + + if (typeof options !== "object") { + throw new Error(`${filepath}: Config returned typeof ${typeof options}`); + } + + if (Array.isArray(options)) { + throw new Error(`${filepath}: Expected config object but found array`); + } + + return { + filepath, + dirname: _path().default.dirname(filepath), + options + }; + }); + const readIgnoreConfig = (0, utils$1.makeStaticFileCache)((filepath, content) => { + const ignoreDir = _path().default.dirname(filepath); + + const ignorePatterns = content.split("\n").map(line => line.replace(/#(.*?)$/, "").trim()).filter(line => !!line); + + for (const pattern of ignorePatterns) { + if (pattern[0] === "!") { + throw new Error(`Negation of file paths is not supported.`); + } + } + + return { + filepath, + dirname: _path().default.dirname(filepath), + ignore: ignorePatterns.map(pattern => (0, _patternToRegex.default)(pattern, ignoreDir)) + }; + }); + + function* resolveShowConfigPath(dirname) { + const targetPath = process.env.BABEL_SHOW_CONFIG_FOR; + + if (targetPath != null) { + const absolutePath = _path().default.resolve(dirname, targetPath); + + const stats = yield* fs$1.stat(absolutePath); + + if (!stats.isFile()) { + throw new Error(`${absolutePath}: BABEL_SHOW_CONFIG_FOR must refer to a regular file, directories are not supported.`); + } + + return absolutePath; + } + + return null; + } + + function throwConfigError() { + throw new Error(`\ +Caching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured +for various types of caching, using the first param of their handler functions: + +module.exports = function(api) { + // The API exposes the following: + + // Cache the returned value forever and don't call this function again. + api.cache(true); + + // Don't cache at all. Not recommended because it will be very slow. + api.cache(false); + + // Cached based on the value of some function. If this function returns a value different from + // a previously-encountered value, the plugins will re-evaluate. + var env = api.cache(() => process.env.NODE_ENV); + + // If testing for a specific env, we recommend specifics to avoid instantiating a plugin for + // any possible NODE_ENV value that might come up during plugin execution. + var isProd = api.cache(() => process.env.NODE_ENV === "production"); + + // .cache(fn) will perform a linear search though instances to find the matching plugin based + // based on previous instantiated plugins. If you want to recreate the plugin and discard the + // previous instance whenever something changes, you may use: + var isProd = api.cache.invalidate(() => process.env.NODE_ENV === "production"); + + // Note, we also expose the following more-verbose versions of the above examples: + api.cache.forever(); // api.cache(true) + api.cache.never(); // api.cache(false) + api.cache.using(fn); // api.cache(fn) + + // Return the value that will be cached. + return { }; +};`); + } + }); + + unwrapExports(configuration); + var configuration_1 = configuration.findConfigUpwards; + var configuration_2 = configuration.findRelativeConfig; + var configuration_3 = configuration.findRootConfig; + var configuration_4 = configuration.loadConfig; + var configuration_5 = configuration.resolveShowConfigPath; + var configuration_6 = configuration.ROOT_CONFIG_FILENAMES; + + var plugins = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.resolvePlugin = resolvePlugin; + exports.resolvePreset = resolvePreset; + exports.loadPlugin = loadPlugin; + exports.loadPreset = loadPreset; + + function _debug() { + const data = _interopRequireDefault(src); + + _debug = function () { + return data; + }; + + return data; + } + + function _resolve() { + const data = _interopRequireDefault(resolve$1); + + _resolve = function () { + return data; + }; + + return data; + } + + function _path() { + const data = _interopRequireDefault(require$$1); + + _path = function () { + return data; + }; + + return data; + } + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + const debug = (0, _debug().default)("babel:config:loading:files:plugins"); + const EXACT_RE = /^module:/; + const BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-plugin-)/; + const BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-preset-)/; + const BABEL_PLUGIN_ORG_RE = /^(@babel\/)(?!plugin-|[^/]+\/)/; + const BABEL_PRESET_ORG_RE = /^(@babel\/)(?!preset-|[^/]+\/)/; + const OTHER_PLUGIN_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-plugin(?:-|\/|$)|[^/]+\/)/; + const OTHER_PRESET_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-preset(?:-|\/|$)|[^/]+\/)/; + const OTHER_ORG_DEFAULT_RE = /^(@(?!babel$)[^/]+)$/; + + function resolvePlugin(name, dirname) { + return resolveStandardizedName("plugin", name, dirname); + } + + function resolvePreset(name, dirname) { + return resolveStandardizedName("preset", name, dirname); + } + + function loadPlugin(name, dirname) { + const filepath = resolvePlugin(name, dirname); + + if (!filepath) { + throw new Error(`Plugin ${name} not found relative to ${dirname}`); + } + + const value = requireModule("plugin", filepath); + debug("Loaded plugin %o from %o.", name, dirname); + return { + filepath, + value + }; + } + + function loadPreset(name, dirname) { + const filepath = resolvePreset(name, dirname); + + if (!filepath) { + throw new Error(`Preset ${name} not found relative to ${dirname}`); + } + + const value = requireModule("preset", filepath); + debug("Loaded preset %o from %o.", name, dirname); + return { + filepath, + value + }; + } + + function standardizeName(type, name) { + if (_path().default.isAbsolute(name)) return name; + const isPreset = type === "preset"; + return name.replace(isPreset ? BABEL_PRESET_PREFIX_RE : BABEL_PLUGIN_PREFIX_RE, `babel-${type}-`).replace(isPreset ? BABEL_PRESET_ORG_RE : BABEL_PLUGIN_ORG_RE, `$1${type}-`).replace(isPreset ? OTHER_PRESET_ORG_RE : OTHER_PLUGIN_ORG_RE, `$1babel-${type}-`).replace(OTHER_ORG_DEFAULT_RE, `$1/babel-${type}`).replace(EXACT_RE, ""); + } + + function resolveStandardizedName(type, name, dirname = process.cwd()) { + const standardizedName = standardizeName(type, name); + + try { + return _resolve().default.sync(standardizedName, { + basedir: dirname + }); + } catch (e) { + if (e.code !== "MODULE_NOT_FOUND") throw e; + + if (standardizedName !== name) { + let resolvedOriginal = false; + + try { + _resolve().default.sync(name, { + basedir: dirname + }); + + resolvedOriginal = true; + } catch (_unused) {} + + if (resolvedOriginal) { + e.message += `\n- If you want to resolve "${name}", use "module:${name}"`; + } + } + + let resolvedBabel = false; + + try { + _resolve().default.sync(standardizeName(type, "@babel/" + name), { + basedir: dirname + }); + + resolvedBabel = true; + } catch (_unused2) {} + + if (resolvedBabel) { + e.message += `\n- Did you mean "@babel/${name}"?`; + } + + let resolvedOppositeType = false; + const oppositeType = type === "preset" ? "plugin" : "preset"; + + try { + _resolve().default.sync(standardizeName(oppositeType, name), { + basedir: dirname + }); + + resolvedOppositeType = true; + } catch (_unused3) {} + + if (resolvedOppositeType) { + e.message += `\n- Did you accidentally pass a ${oppositeType} as a ${type}?`; + } + + throw e; + } + } + + const LOADING_MODULES = new Set(); + + function requireModule(type, name) { + if (LOADING_MODULES.has(name)) { + throw new Error(`Reentrant ${type} detected trying to load "${name}". This module is not ignored ` + "and is trying to load itself while compiling itself, leading to a dependency cycle. " + 'We recommend adding it to your "ignore" list in your babelrc, or to a .babelignore.'); + } + + try { + LOADING_MODULES.add(name); + return commonjsRequire(name); + } finally { + LOADING_MODULES.delete(name); + } + } + }); + + unwrapExports(plugins); + var plugins_1 = plugins.resolvePlugin; + var plugins_2 = plugins.resolvePreset; + var plugins_3 = plugins.loadPlugin; + var plugins_4 = plugins.loadPreset; + + var files = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + Object.defineProperty(exports, "findPackageData", { + enumerable: true, + get: function () { + return _package.findPackageData; + } + }); + Object.defineProperty(exports, "findConfigUpwards", { + enumerable: true, + get: function () { + return configuration.findConfigUpwards; + } + }); + Object.defineProperty(exports, "findRelativeConfig", { + enumerable: true, + get: function () { + return configuration.findRelativeConfig; + } + }); + Object.defineProperty(exports, "findRootConfig", { + enumerable: true, + get: function () { + return configuration.findRootConfig; + } + }); + Object.defineProperty(exports, "loadConfig", { + enumerable: true, + get: function () { + return configuration.loadConfig; + } + }); + Object.defineProperty(exports, "resolveShowConfigPath", { + enumerable: true, + get: function () { + return configuration.resolveShowConfigPath; + } + }); + Object.defineProperty(exports, "ROOT_CONFIG_FILENAMES", { + enumerable: true, + get: function () { + return configuration.ROOT_CONFIG_FILENAMES; + } + }); + Object.defineProperty(exports, "resolvePlugin", { + enumerable: true, + get: function () { + return plugins.resolvePlugin; + } + }); + Object.defineProperty(exports, "resolvePreset", { + enumerable: true, + get: function () { + return plugins.resolvePreset; + } + }); + Object.defineProperty(exports, "loadPlugin", { + enumerable: true, + get: function () { + return plugins.loadPlugin; + } + }); + Object.defineProperty(exports, "loadPreset", { + enumerable: true, + get: function () { + return plugins.loadPreset; + } + }); + }); + + unwrapExports(files); + + var name = "@babel/core"; + var version$1 = "7.12.7"; + var description = "Babel compiler core."; + var main = "lib/index.js"; + var author = "Sebastian McKenzie "; + var homepage = "https://babeljs.io/"; + var license = "MIT"; + var publishConfig = { + access: "public" + }; + var repository = { + type: "git", + url: "https://github.com/babel/babel.git", + directory: "packages/babel-core" + }; + var keywords = [ + "6to5", + "babel", + "classes", + "const", + "es6", + "harmony", + "let", + "modules", + "transpile", + "transpiler", + "var", + "babel-core", + "compiler" + ]; + var engines = { + node: ">=6.9.0" + }; + var funding = { + type: "opencollective", + url: "https://opencollective.com/babel" + }; + var browser$4 = { + "./lib/config/files/index.js": "./lib/config/files/index-browser.js", + "./lib/transform-file.js": "./lib/transform-file-browser.js", + "./src/config/files/index.js": "./src/config/files/index-browser.js", + "./src/transform-file.js": "./src/transform-file-browser.js" + }; + var dependencies = { + "@babel/code-frame": "^7.10.4", + "@babel/generator": "^7.12.5", + "@babel/helper-module-transforms": "^7.12.1", + "@babel/helpers": "^7.12.5", + "@babel/parser": "^7.12.7", + "@babel/template": "^7.12.7", + "@babel/traverse": "^7.12.7", + "@babel/types": "^7.12.7", + "convert-source-map": "^1.7.0", + debug: "^4.1.0", + gensync: "^1.0.0-beta.1", + json5: "^2.1.2", + lodash: "^4.17.19", + resolve: "^1.3.2", + semver: "^5.4.1", + "source-map": "^0.5.0" + }; + var devDependencies = { + "@babel/helper-transform-fixture-test-runner": "7.12.1" + }; + var _package$1 = { + name: name, + version: version$1, + description: description, + main: main, + author: author, + homepage: homepage, + license: license, + publishConfig: publishConfig, + repository: repository, + keywords: keywords, + engines: engines, + funding: funding, + browser: browser$4, + dependencies: dependencies, + devDependencies: devDependencies + }; + + var _package$2 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name, + version: version$1, + description: description, + main: main, + author: author, + homepage: homepage, + license: license, + publishConfig: publishConfig, + repository: repository, + keywords: keywords, + engines: engines, + funding: funding, + browser: browser$4, + dependencies: dependencies, + devDependencies: devDependencies, + 'default': _package$1 + }); + + var environment = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.getEnv = getEnv; + + function getEnv(defaultValue = "development") { + return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue; + } + }); + + unwrapExports(environment); + var environment_1 = environment.getEnv; + + var configDescriptors = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.createCachedDescriptors = createCachedDescriptors; + exports.createUncachedDescriptors = createUncachedDescriptors; + exports.createDescriptor = createDescriptor; + + + + + + + + function isEqualDescriptor(a, b) { + return a.name === b.name && a.value === b.value && a.options === b.options && a.dirname === b.dirname && a.alias === b.alias && a.ownPass === b.ownPass && (a.file && a.file.request) === (b.file && b.file.request) && (a.file && a.file.resolved) === (b.file && b.file.resolved); + } + + function createCachedDescriptors(dirname, options, alias) { + const { + plugins, + presets, + passPerPreset + } = options; + return { + options, + plugins: plugins ? () => createCachedPluginDescriptors(plugins, dirname)(alias) : () => [], + presets: presets ? () => createCachedPresetDescriptors(presets, dirname)(alias)(!!passPerPreset) : () => [] + }; + } + + function createUncachedDescriptors(dirname, options, alias) { + let plugins; + let presets; + return { + options, + plugins: () => { + if (!plugins) { + plugins = createPluginDescriptors(options.plugins || [], dirname, alias); + } + + return plugins; + }, + presets: () => { + if (!presets) { + presets = createPresetDescriptors(options.presets || [], dirname, alias, !!options.passPerPreset); + } + + return presets; + } + }; + } + + const PRESET_DESCRIPTOR_CACHE = new WeakMap(); + const createCachedPresetDescriptors = (0, caching.makeWeakCacheSync)((items, cache) => { + const dirname = cache.using(dir => dir); + return (0, caching.makeStrongCacheSync)(alias => (0, caching.makeStrongCacheSync)(passPerPreset => createPresetDescriptors(items, dirname, alias, passPerPreset).map(desc => loadCachedDescriptor(PRESET_DESCRIPTOR_CACHE, desc)))); + }); + const PLUGIN_DESCRIPTOR_CACHE = new WeakMap(); + const createCachedPluginDescriptors = (0, caching.makeWeakCacheSync)((items, cache) => { + const dirname = cache.using(dir => dir); + return (0, caching.makeStrongCacheSync)(alias => createPluginDescriptors(items, dirname, alias).map(desc => loadCachedDescriptor(PLUGIN_DESCRIPTOR_CACHE, desc))); + }); + const DEFAULT_OPTIONS = {}; + + function loadCachedDescriptor(cache, desc) { + const { + value, + options = DEFAULT_OPTIONS + } = desc; + if (options === false) return desc; + let cacheByOptions = cache.get(value); + + if (!cacheByOptions) { + cacheByOptions = new WeakMap(); + cache.set(value, cacheByOptions); + } + + let possibilities = cacheByOptions.get(options); + + if (!possibilities) { + possibilities = []; + cacheByOptions.set(options, possibilities); + } + + if (possibilities.indexOf(desc) === -1) { + const matches = possibilities.filter(possibility => isEqualDescriptor(possibility, desc)); + + if (matches.length > 0) { + return matches[0]; + } + + possibilities.push(desc); + } + + return desc; + } + + function createPresetDescriptors(items, dirname, alias, passPerPreset) { + return createDescriptors("preset", items, dirname, alias, passPerPreset); + } + + function createPluginDescriptors(items, dirname, alias) { + return createDescriptors("plugin", items, dirname, alias); + } + + function createDescriptors(type, items, dirname, alias, ownPass) { + const descriptors = items.map((item, index) => createDescriptor(item, dirname, { + type, + alias: `${alias}$${index}`, + ownPass: !!ownPass + })); + assertNoDuplicates(descriptors); + return descriptors; + } + + function createDescriptor(pair, dirname, { + type, + alias, + ownPass + }) { + const desc = (0, item.getItemDescriptor)(pair); + + if (desc) { + return desc; + } + + let name; + let options; + let value = pair; + + if (Array.isArray(value)) { + if (value.length === 3) { + [value, options, name] = value; + } else { + [value, options] = value; + } + } + + let file = undefined; + let filepath = null; + + if (typeof value === "string") { + if (typeof type !== "string") { + throw new Error("To resolve a string-based item, the type of item must be given"); + } + + const resolver = type === "plugin" ? files.loadPlugin : files.loadPreset; + const request = value; + ({ + filepath, + value + } = resolver(value, dirname)); + file = { + request, + resolved: filepath + }; + } + + if (!value) { + throw new Error(`Unexpected falsy value: ${String(value)}`); + } + + if (typeof value === "object" && value.__esModule) { + if (value.default) { + value = value.default; + } else { + throw new Error("Must export a default export when using ES6 modules."); + } + } + + if (typeof value !== "object" && typeof value !== "function") { + throw new Error(`Unsupported format: ${typeof value}. Expected an object or a function.`); + } + + if (filepath !== null && typeof value === "object" && value) { + throw new Error(`Plugin/Preset files are not allowed to export objects, only functions. In ${filepath}`); + } + + return { + name, + alias: filepath || alias, + value, + options, + dirname, + ownPass, + file + }; + } + + function assertNoDuplicates(items) { + const map = new Map(); + + for (const item of items) { + if (typeof item.value !== "function") continue; + let nameMap = map.get(item.value); + + if (!nameMap) { + nameMap = new Set(); + map.set(item.value, nameMap); + } + + if (nameMap.has(item.name)) { + const conflicts = items.filter(i => i.value === item.value); + throw new Error([`Duplicate plugin/preset detected.`, `If you'd like to use two separate instances of a plugin,`, `they need separate names, e.g.`, ``, ` plugins: [`, ` ['some-plugin', {}],`, ` ['some-plugin', {}, 'some unique name'],`, ` ]`, ``, `Duplicates detected are:`, `${JSON.stringify(conflicts, null, 2)}`].join("\n")); + } + + nameMap.add(item.name); + } + } + }); + + unwrapExports(configDescriptors); + var configDescriptors_1 = configDescriptors.createCachedDescriptors; + var configDescriptors_2 = configDescriptors.createUncachedDescriptors; + var configDescriptors_3 = configDescriptors.createDescriptor; + + var item = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.createItemFromDescriptor = createItemFromDescriptor; + exports.createConfigItem = createConfigItem; + exports.getItemDescriptor = getItemDescriptor; + + function _path() { + const data = _interopRequireDefault(require$$1); + + _path = function () { + return data; + }; + + return data; + } + + + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function createItemFromDescriptor(desc) { + return new ConfigItem(desc); + } + + function createConfigItem(value, { + dirname = ".", + type + } = {}) { + const descriptor = (0, configDescriptors.createDescriptor)(value, _path().default.resolve(dirname), { + type, + alias: "programmatic item" + }); + return createItemFromDescriptor(descriptor); + } + + function getItemDescriptor(item) { + if (item == null ? void 0 : item[CONFIG_ITEM_BRAND]) { + return item._descriptor; + } + + return undefined; + } + + const CONFIG_ITEM_BRAND = Symbol.for("@babel/core@7 - ConfigItem"); + + class ConfigItem { + constructor(descriptor) { + this._descriptor = void 0; + this[CONFIG_ITEM_BRAND] = true; + this.value = void 0; + this.options = void 0; + this.dirname = void 0; + this.name = void 0; + this.file = void 0; + this._descriptor = descriptor; + Object.defineProperty(this, "_descriptor", { + enumerable: false + }); + Object.defineProperty(this, CONFIG_ITEM_BRAND, { + enumerable: false + }); + this.value = this._descriptor.value; + this.options = this._descriptor.options; + this.dirname = this._descriptor.dirname; + this.name = this._descriptor.name; + this.file = this._descriptor.file ? { + request: this._descriptor.file.request, + resolved: this._descriptor.file.resolved + } : undefined; + Object.freeze(this); + } + + } + + Object.freeze(ConfigItem.prototype); + }); + + unwrapExports(item); + var item_1 = item.createItemFromDescriptor; + var item_2 = item.createConfigItem; + var item_3 = item.getItemDescriptor; + + var plugin = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = void 0; + + class Plugin { + constructor(plugin, options, key) { + this.key = void 0; + this.manipulateOptions = void 0; + this.post = void 0; + this.pre = void 0; + this.visitor = void 0; + this.parserOverride = void 0; + this.generatorOverride = void 0; + this.options = void 0; + this.key = plugin.name || key; + this.manipulateOptions = plugin.manipulateOptions; + this.post = plugin.post; + this.pre = plugin.pre; + this.visitor = plugin.visitor || {}; + this.parserOverride = plugin.parserOverride; + this.generatorOverride = plugin.generatorOverride; + this.options = options; + } + + } + + exports.default = Plugin; + }); + + unwrapExports(plugin); + + var removed = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = void 0; + var _default = { + auxiliaryComment: { + message: "Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`" + }, + blacklist: { + message: "Put the specific transforms you want in the `plugins` option" + }, + breakConfig: { + message: "This is not a necessary option in Babel 6" + }, + experimental: { + message: "Put the specific transforms you want in the `plugins` option" + }, + externalHelpers: { + message: "Use the `external-helpers` plugin instead. " + "Check out http://babeljs.io/docs/plugins/external-helpers/" + }, + extra: { + message: "" + }, + jsxPragma: { + message: "use the `pragma` option in the `react-jsx` plugin. " + "Check out http://babeljs.io/docs/plugins/transform-react-jsx/" + }, + loose: { + message: "Specify the `loose` option for the relevant plugin you are using " + "or use a preset that sets the option." + }, + metadataUsedHelpers: { + message: "Not required anymore as this is enabled by default" + }, + modules: { + message: "Use the corresponding module transform plugin in the `plugins` option. " + "Check out http://babeljs.io/docs/plugins/#modules" + }, + nonStandard: { + message: "Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. " + "Also check out the react preset http://babeljs.io/docs/plugins/preset-react/" + }, + optional: { + message: "Put the specific transforms you want in the `plugins` option" + }, + sourceMapName: { + message: "The `sourceMapName` option has been removed because it makes more sense for the " + "tooling that calls Babel to assign `map.file` themselves." + }, + stage: { + message: "Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets" + }, + whitelist: { + message: "Put the specific transforms you want in the `plugins` option" + }, + resolveModuleSource: { + version: 6, + message: "Use `babel-plugin-module-resolver@3`'s 'resolvePath' options" + }, + metadata: { + version: 6, + message: "Generated plugin metadata is always included in the output result" + }, + sourceMapTarget: { + version: 6, + message: "The `sourceMapTarget` option has been removed because it makes more sense for the tooling " + "that calls Babel to assign `map.file` themselves." + } + }; + exports.default = _default; + }); + + unwrapExports(removed); + + var optionAssertions = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.msg = msg; + exports.access = access; + exports.assertRootMode = assertRootMode; + exports.assertSourceMaps = assertSourceMaps; + exports.assertCompact = assertCompact; + exports.assertSourceType = assertSourceType; + exports.assertCallerMetadata = assertCallerMetadata; + exports.assertInputSourceMap = assertInputSourceMap; + exports.assertString = assertString; + exports.assertFunction = assertFunction; + exports.assertBoolean = assertBoolean; + exports.assertObject = assertObject; + exports.assertArray = assertArray; + exports.assertIgnoreList = assertIgnoreList; + exports.assertConfigApplicableTest = assertConfigApplicableTest; + exports.assertConfigFileSearch = assertConfigFileSearch; + exports.assertBabelrcSearch = assertBabelrcSearch; + exports.assertPluginList = assertPluginList; + + function msg(loc) { + switch (loc.type) { + case "root": + return ``; + + case "env": + return `${msg(loc.parent)}.env["${loc.name}"]`; + + case "overrides": + return `${msg(loc.parent)}.overrides[${loc.index}]`; + + case "option": + return `${msg(loc.parent)}.${loc.name}`; + + case "access": + return `${msg(loc.parent)}[${JSON.stringify(loc.name)}]`; + + default: + throw new Error(`Assertion failure: Unknown type ${loc.type}`); + } + } + + function access(loc, name) { + return { + type: "access", + name, + parent: loc + }; + } + + function assertRootMode(loc, value) { + if (value !== undefined && value !== "root" && value !== "upward" && value !== "upward-optional") { + throw new Error(`${msg(loc)} must be a "root", "upward", "upward-optional" or undefined`); + } + + return value; + } + + function assertSourceMaps(loc, value) { + if (value !== undefined && typeof value !== "boolean" && value !== "inline" && value !== "both") { + throw new Error(`${msg(loc)} must be a boolean, "inline", "both", or undefined`); + } + + return value; + } + + function assertCompact(loc, value) { + if (value !== undefined && typeof value !== "boolean" && value !== "auto") { + throw new Error(`${msg(loc)} must be a boolean, "auto", or undefined`); + } + + return value; + } + + function assertSourceType(loc, value) { + if (value !== undefined && value !== "module" && value !== "script" && value !== "unambiguous") { + throw new Error(`${msg(loc)} must be "module", "script", "unambiguous", or undefined`); + } + + return value; + } + + function assertCallerMetadata(loc, value) { + const obj = assertObject(loc, value); + + if (obj) { + if (typeof obj["name"] !== "string") { + throw new Error(`${msg(loc)} set but does not contain "name" property string`); + } + + for (const prop of Object.keys(obj)) { + const propLoc = access(loc, prop); + const value = obj[prop]; + + if (value != null && typeof value !== "boolean" && typeof value !== "string" && typeof value !== "number") { + throw new Error(`${msg(propLoc)} must be null, undefined, a boolean, a string, or a number.`); + } + } + } + + return value; + } + + function assertInputSourceMap(loc, value) { + if (value !== undefined && typeof value !== "boolean" && (typeof value !== "object" || !value)) { + throw new Error(`${msg(loc)} must be a boolean, object, or undefined`); + } + + return value; + } + + function assertString(loc, value) { + if (value !== undefined && typeof value !== "string") { + throw new Error(`${msg(loc)} must be a string, or undefined`); + } + + return value; + } + + function assertFunction(loc, value) { + if (value !== undefined && typeof value !== "function") { + throw new Error(`${msg(loc)} must be a function, or undefined`); + } + + return value; + } + + function assertBoolean(loc, value) { + if (value !== undefined && typeof value !== "boolean") { + throw new Error(`${msg(loc)} must be a boolean, or undefined`); + } + + return value; + } + + function assertObject(loc, value) { + if (value !== undefined && (typeof value !== "object" || Array.isArray(value) || !value)) { + throw new Error(`${msg(loc)} must be an object, or undefined`); + } + + return value; + } + + function assertArray(loc, value) { + if (value != null && !Array.isArray(value)) { + throw new Error(`${msg(loc)} must be an array, or undefined`); + } + + return value; + } + + function assertIgnoreList(loc, value) { + const arr = assertArray(loc, value); + + if (arr) { + arr.forEach((item, i) => assertIgnoreItem(access(loc, i), item)); + } + + return arr; + } + + function assertIgnoreItem(loc, value) { + if (typeof value !== "string" && typeof value !== "function" && !(value instanceof RegExp)) { + throw new Error(`${msg(loc)} must be an array of string/Function/RegExp values, or undefined`); + } + + return value; + } + + function assertConfigApplicableTest(loc, value) { + if (value === undefined) return value; + + if (Array.isArray(value)) { + value.forEach((item, i) => { + if (!checkValidTest(item)) { + throw new Error(`${msg(access(loc, i))} must be a string/Function/RegExp.`); + } + }); + } else if (!checkValidTest(value)) { + throw new Error(`${msg(loc)} must be a string/Function/RegExp, or an array of those`); + } + + return value; + } + + function checkValidTest(value) { + return typeof value === "string" || typeof value === "function" || value instanceof RegExp; + } + + function assertConfigFileSearch(loc, value) { + if (value !== undefined && typeof value !== "boolean" && typeof value !== "string") { + throw new Error(`${msg(loc)} must be a undefined, a boolean, a string, ` + `got ${JSON.stringify(value)}`); + } + + return value; + } + + function assertBabelrcSearch(loc, value) { + if (value === undefined || typeof value === "boolean") return value; + + if (Array.isArray(value)) { + value.forEach((item, i) => { + if (!checkValidTest(item)) { + throw new Error(`${msg(access(loc, i))} must be a string/Function/RegExp.`); + } + }); + } else if (!checkValidTest(value)) { + throw new Error(`${msg(loc)} must be a undefined, a boolean, a string/Function/RegExp ` + `or an array of those, got ${JSON.stringify(value)}`); + } + + return value; + } + + function assertPluginList(loc, value) { + const arr = assertArray(loc, value); + + if (arr) { + arr.forEach((item, i) => assertPluginItem(access(loc, i), item)); + } + + return arr; + } + + function assertPluginItem(loc, value) { + if (Array.isArray(value)) { + if (value.length === 0) { + throw new Error(`${msg(loc)} must include an object`); + } + + if (value.length > 3) { + throw new Error(`${msg(loc)} may only be a two-tuple or three-tuple`); + } + + assertPluginTarget(access(loc, 0), value[0]); + + if (value.length > 1) { + const opts = value[1]; + + if (opts !== undefined && opts !== false && (typeof opts !== "object" || Array.isArray(opts) || opts === null)) { + throw new Error(`${msg(access(loc, 1))} must be an object, false, or undefined`); + } + } + + if (value.length === 3) { + const name = value[2]; + + if (name !== undefined && typeof name !== "string") { + throw new Error(`${msg(access(loc, 2))} must be a string, or undefined`); + } + } + } else { + assertPluginTarget(loc, value); + } + + return value; + } + + function assertPluginTarget(loc, value) { + if ((typeof value !== "object" || !value) && typeof value !== "string" && typeof value !== "function") { + throw new Error(`${msg(loc)} must be a string, object, function`); + } + + return value; + } + }); + + unwrapExports(optionAssertions); + var optionAssertions_1 = optionAssertions.msg; + var optionAssertions_2 = optionAssertions.access; + var optionAssertions_3 = optionAssertions.assertRootMode; + var optionAssertions_4 = optionAssertions.assertSourceMaps; + var optionAssertions_5 = optionAssertions.assertCompact; + var optionAssertions_6 = optionAssertions.assertSourceType; + var optionAssertions_7 = optionAssertions.assertCallerMetadata; + var optionAssertions_8 = optionAssertions.assertInputSourceMap; + var optionAssertions_9 = optionAssertions.assertString; + var optionAssertions_10 = optionAssertions.assertFunction; + var optionAssertions_11 = optionAssertions.assertBoolean; + var optionAssertions_12 = optionAssertions.assertObject; + var optionAssertions_13 = optionAssertions.assertArray; + var optionAssertions_14 = optionAssertions.assertIgnoreList; + var optionAssertions_15 = optionAssertions.assertConfigApplicableTest; + var optionAssertions_16 = optionAssertions.assertConfigFileSearch; + var optionAssertions_17 = optionAssertions.assertBabelrcSearch; + var optionAssertions_18 = optionAssertions.assertPluginList; + + var options$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.validate = validate; + exports.checkNoUnwrappedItemOptionPairs = checkNoUnwrappedItemOptionPairs; + + var _plugin = _interopRequireDefault(plugin); + + var _removed = _interopRequireDefault(removed); + + + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + const ROOT_VALIDATORS = { + cwd: optionAssertions.assertString, + root: optionAssertions.assertString, + rootMode: optionAssertions.assertRootMode, + configFile: optionAssertions.assertConfigFileSearch, + caller: optionAssertions.assertCallerMetadata, + filename: optionAssertions.assertString, + filenameRelative: optionAssertions.assertString, + code: optionAssertions.assertBoolean, + ast: optionAssertions.assertBoolean, + cloneInputAst: optionAssertions.assertBoolean, + envName: optionAssertions.assertString + }; + const BABELRC_VALIDATORS = { + babelrc: optionAssertions.assertBoolean, + babelrcRoots: optionAssertions.assertBabelrcSearch + }; + const NONPRESET_VALIDATORS = { + extends: optionAssertions.assertString, + ignore: optionAssertions.assertIgnoreList, + only: optionAssertions.assertIgnoreList + }; + const COMMON_VALIDATORS = { + inputSourceMap: optionAssertions.assertInputSourceMap, + presets: optionAssertions.assertPluginList, + plugins: optionAssertions.assertPluginList, + passPerPreset: optionAssertions.assertBoolean, + env: assertEnvSet, + overrides: assertOverridesList, + test: optionAssertions.assertConfigApplicableTest, + include: optionAssertions.assertConfigApplicableTest, + exclude: optionAssertions.assertConfigApplicableTest, + retainLines: optionAssertions.assertBoolean, + comments: optionAssertions.assertBoolean, + shouldPrintComment: optionAssertions.assertFunction, + compact: optionAssertions.assertCompact, + minified: optionAssertions.assertBoolean, + auxiliaryCommentBefore: optionAssertions.assertString, + auxiliaryCommentAfter: optionAssertions.assertString, + sourceType: optionAssertions.assertSourceType, + wrapPluginVisitorMethod: optionAssertions.assertFunction, + highlightCode: optionAssertions.assertBoolean, + sourceMaps: optionAssertions.assertSourceMaps, + sourceMap: optionAssertions.assertSourceMaps, + sourceFileName: optionAssertions.assertString, + sourceRoot: optionAssertions.assertString, + getModuleId: optionAssertions.assertFunction, + moduleRoot: optionAssertions.assertString, + moduleIds: optionAssertions.assertBoolean, + moduleId: optionAssertions.assertString, + parserOpts: optionAssertions.assertObject, + generatorOpts: optionAssertions.assertObject + }; + + function getSource(loc) { + return loc.type === "root" ? loc.source : getSource(loc.parent); + } + + function validate(type, opts) { + return validateNested({ + type: "root", + source: type + }, opts); + } + + function validateNested(loc, opts) { + const type = getSource(loc); + assertNoDuplicateSourcemap(opts); + Object.keys(opts).forEach(key => { + const optLoc = { + type: "option", + name: key, + parent: loc + }; + + if (type === "preset" && NONPRESET_VALIDATORS[key]) { + throw new Error(`${(0, optionAssertions.msg)(optLoc)} is not allowed in preset options`); + } + + if (type !== "arguments" && ROOT_VALIDATORS[key]) { + throw new Error(`${(0, optionAssertions.msg)(optLoc)} is only allowed in root programmatic options`); + } + + if (type !== "arguments" && type !== "configfile" && BABELRC_VALIDATORS[key]) { + if (type === "babelrcfile" || type === "extendsfile") { + throw new Error(`${(0, optionAssertions.msg)(optLoc)} is not allowed in .babelrc or "extends"ed files, only in root programmatic options, ` + `or babel.config.js/config file options`); + } + + throw new Error(`${(0, optionAssertions.msg)(optLoc)} is only allowed in root programmatic options, or babel.config.js/config file options`); + } + + const validator = COMMON_VALIDATORS[key] || NONPRESET_VALIDATORS[key] || BABELRC_VALIDATORS[key] || ROOT_VALIDATORS[key] || throwUnknownError; + validator(optLoc, opts[key]); + }); + return opts; + } + + function throwUnknownError(loc) { + const key = loc.name; + + if (_removed.default[key]) { + const { + message, + version = 5 + } = _removed.default[key]; + throw new Error(`Using removed Babel ${version} option: ${(0, optionAssertions.msg)(loc)} - ${message}`); + } else { + const unknownOptErr = new Error(`Unknown option: ${(0, optionAssertions.msg)(loc)}. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.`); + unknownOptErr.code = "BABEL_UNKNOWN_OPTION"; + throw unknownOptErr; + } + } + + function has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); + } + + function assertNoDuplicateSourcemap(opts) { + if (has(opts, "sourceMap") && has(opts, "sourceMaps")) { + throw new Error(".sourceMap is an alias for .sourceMaps, cannot use both"); + } + } + + function assertEnvSet(loc, value) { + if (loc.parent.type === "env") { + throw new Error(`${(0, optionAssertions.msg)(loc)} is not allowed inside of another .env block`); + } + + const parent = loc.parent; + const obj = (0, optionAssertions.assertObject)(loc, value); + + if (obj) { + for (const envName of Object.keys(obj)) { + const env = (0, optionAssertions.assertObject)((0, optionAssertions.access)(loc, envName), obj[envName]); + if (!env) continue; + const envLoc = { + type: "env", + name: envName, + parent + }; + validateNested(envLoc, env); + } + } + + return obj; + } + + function assertOverridesList(loc, value) { + if (loc.parent.type === "env") { + throw new Error(`${(0, optionAssertions.msg)(loc)} is not allowed inside an .env block`); + } + + if (loc.parent.type === "overrides") { + throw new Error(`${(0, optionAssertions.msg)(loc)} is not allowed inside an .overrides block`); + } + + const parent = loc.parent; + const arr = (0, optionAssertions.assertArray)(loc, value); + + if (arr) { + for (const [index, item] of arr.entries()) { + const objLoc = (0, optionAssertions.access)(loc, index); + const env = (0, optionAssertions.assertObject)(objLoc, item); + if (!env) throw new Error(`${(0, optionAssertions.msg)(objLoc)} must be an object`); + const overridesLoc = { + type: "overrides", + index, + parent + }; + validateNested(overridesLoc, env); + } + } + + return arr; + } + + function checkNoUnwrappedItemOptionPairs(items, index, type, e) { + if (index === 0) return; + const lastItem = items[index - 1]; + const thisItem = items[index]; + + if (lastItem.file && lastItem.options === undefined && typeof thisItem.value === "object") { + e.message += `\n- Maybe you meant to use\n` + `"${type}": [\n ["${lastItem.file.request}", ${JSON.stringify(thisItem.value, undefined, 2)}]\n]\n` + `To be a valid ${type}, its name and options should be wrapped in a pair of brackets`; + } + } + }); + + unwrapExports(options$1); + var options_1$1 = options$1.validate; + var options_2$1 = options$1.checkNoUnwrappedItemOptionPairs; + + var printer$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.ConfigPrinter = exports.ChainFormatter = void 0; + const ChainFormatter = { + Programmatic: 0, + Config: 1 + }; + exports.ChainFormatter = ChainFormatter; + const Formatter = { + title(type, callerName, filepath) { + let title = ""; + + if (type === ChainFormatter.Programmatic) { + title = "programmatic options"; + + if (callerName) { + title += " from " + callerName; + } + } else { + title = "config " + filepath; + } + + return title; + }, + + loc(index, envName) { + let loc = ""; + + if (index != null) { + loc += `.overrides[${index}]`; + } + + if (envName != null) { + loc += `.env["${envName}"]`; + } + + return loc; + }, + + optionsAndDescriptors(opt) { + const content = Object.assign({}, opt.options); + delete content.overrides; + delete content.env; + const pluginDescriptors = [...opt.plugins()]; + + if (pluginDescriptors.length) { + content.plugins = pluginDescriptors.map(d => descriptorToConfig(d)); + } + + const presetDescriptors = [...opt.presets()]; + + if (presetDescriptors.length) { + content.presets = [...presetDescriptors].map(d => descriptorToConfig(d)); + } + + return JSON.stringify(content, undefined, 2); + } + + }; + + function descriptorToConfig(d) { + var _d$file; + + let name = (_d$file = d.file) == null ? void 0 : _d$file.request; + + if (name == null) { + if (typeof d.value === "object") { + name = d.value; + } else if (typeof d.value === "function") { + name = `[Function: ${d.value.toString().substr(0, 50)} ... ]`; + } + } + + if (name == null) { + name = "[Unknown]"; + } + + if (d.options === undefined) { + return name; + } else if (d.name == null) { + return [name, d.options]; + } else { + return [name, d.options, d.name]; + } + } + + class ConfigPrinter { + constructor() { + this._stack = []; + } + + configure(enabled, type, { + callerName, + filepath + }) { + if (!enabled) return () => {}; + return (content, index, envName) => { + this._stack.push({ + type, + callerName, + filepath, + content, + index, + envName + }); + }; + } + + static format(config) { + let title = Formatter.title(config.type, config.callerName, config.filepath); + const loc = Formatter.loc(config.index, config.envName); + if (loc) title += ` ${loc}`; + const content = Formatter.optionsAndDescriptors(config.content); + return `${title}\n${content}`; + } + + output() { + if (this._stack.length === 0) return ""; + return this._stack.map(s => ConfigPrinter.format(s)).join("\n\n"); + } + + } + + exports.ConfigPrinter = ConfigPrinter; + }); + + unwrapExports(printer$1); + var printer_1 = printer$1.ConfigPrinter; + var printer_2 = printer$1.ChainFormatter; + + var configChain = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.buildPresetChain = buildPresetChain; + exports.buildRootChain = buildRootChain; + exports.buildPresetChainWalker = void 0; + + function _path() { + const data = _interopRequireDefault(require$$1); + + _path = function () { + return data; + }; + + return data; + } + + function _debug() { + const data = _interopRequireDefault(src); + + _debug = function () { + return data; + }; + + return data; + } + + + + var _patternToRegex = _interopRequireDefault(patternToRegex); + + + + + + + + + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + const debug = (0, _debug().default)("babel:config:config-chain"); + + function* buildPresetChain(arg, context) { + const chain = yield* buildPresetChainWalker(arg, context); + if (!chain) return null; + return { + plugins: dedupDescriptors(chain.plugins), + presets: dedupDescriptors(chain.presets), + options: chain.options.map(o => normalizeOptions(o)), + files: new Set() + }; + } + + const buildPresetChainWalker = makeChainWalker({ + root: preset => loadPresetDescriptors(preset), + env: (preset, envName) => loadPresetEnvDescriptors(preset)(envName), + overrides: (preset, index) => loadPresetOverridesDescriptors(preset)(index), + overridesEnv: (preset, index, envName) => loadPresetOverridesEnvDescriptors(preset)(index)(envName), + createLogger: () => () => {} + }); + exports.buildPresetChainWalker = buildPresetChainWalker; + const loadPresetDescriptors = (0, caching.makeWeakCacheSync)(preset => buildRootDescriptors(preset, preset.alias, configDescriptors.createUncachedDescriptors)); + const loadPresetEnvDescriptors = (0, caching.makeWeakCacheSync)(preset => (0, caching.makeStrongCacheSync)(envName => buildEnvDescriptors(preset, preset.alias, configDescriptors.createUncachedDescriptors, envName))); + const loadPresetOverridesDescriptors = (0, caching.makeWeakCacheSync)(preset => (0, caching.makeStrongCacheSync)(index => buildOverrideDescriptors(preset, preset.alias, configDescriptors.createUncachedDescriptors, index))); + const loadPresetOverridesEnvDescriptors = (0, caching.makeWeakCacheSync)(preset => (0, caching.makeStrongCacheSync)(index => (0, caching.makeStrongCacheSync)(envName => buildOverrideEnvDescriptors(preset, preset.alias, configDescriptors.createUncachedDescriptors, index, envName)))); + + function* buildRootChain(opts, context) { + let configReport, babelRcReport; + const programmaticLogger = new printer$1.ConfigPrinter(); + const programmaticChain = yield* loadProgrammaticChain({ + options: opts, + dirname: context.cwd + }, context, undefined, programmaticLogger); + if (!programmaticChain) return null; + const programmaticReport = programmaticLogger.output(); + let configFile; + + if (typeof opts.configFile === "string") { + configFile = yield* (0, files.loadConfig)(opts.configFile, context.cwd, context.envName, context.caller); + } else if (opts.configFile !== false) { + configFile = yield* (0, files.findRootConfig)(context.root, context.envName, context.caller); + } + + let { + babelrc, + babelrcRoots + } = opts; + let babelrcRootsDirectory = context.cwd; + const configFileChain = emptyChain(); + const configFileLogger = new printer$1.ConfigPrinter(); + + if (configFile) { + const validatedFile = validateConfigFile(configFile); + const result = yield* loadFileChain(validatedFile, context, undefined, configFileLogger); + if (!result) return null; + configReport = configFileLogger.output(); + + if (babelrc === undefined) { + babelrc = validatedFile.options.babelrc; + } + + if (babelrcRoots === undefined) { + babelrcRootsDirectory = validatedFile.dirname; + babelrcRoots = validatedFile.options.babelrcRoots; + } + + mergeChain(configFileChain, result); + } + + const pkgData = typeof context.filename === "string" ? yield* (0, files.findPackageData)(context.filename) : null; + let ignoreFile, babelrcFile; + let isIgnored = false; + const fileChain = emptyChain(); + + if ((babelrc === true || babelrc === undefined) && pkgData && babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory)) { + ({ + ignore: ignoreFile, + config: babelrcFile + } = yield* (0, files.findRelativeConfig)(pkgData, context.envName, context.caller)); + + if (ignoreFile) { + fileChain.files.add(ignoreFile.filepath); + } + + if (ignoreFile && shouldIgnore(context, ignoreFile.ignore, null, ignoreFile.dirname)) { + isIgnored = true; + } + + if (babelrcFile && !isIgnored) { + const validatedFile = validateBabelrcFile(babelrcFile); + const babelrcLogger = new printer$1.ConfigPrinter(); + const result = yield* loadFileChain(validatedFile, context, undefined, babelrcLogger); + + if (!result) { + isIgnored = true; + } else { + babelRcReport = babelrcLogger.output(); + mergeChain(fileChain, result); + } + } + + if (babelrcFile && isIgnored) { + fileChain.files.add(babelrcFile.filepath); + } + } + + if (context.showConfig) { + console.log(`Babel configs on "${context.filename}" (ascending priority):\n` + [configReport, babelRcReport, programmaticReport].filter(x => !!x).join("\n\n")); + return null; + } + + const chain = mergeChain(mergeChain(mergeChain(emptyChain(), configFileChain), fileChain), programmaticChain); + return { + plugins: isIgnored ? [] : dedupDescriptors(chain.plugins), + presets: isIgnored ? [] : dedupDescriptors(chain.presets), + options: isIgnored ? [] : chain.options.map(o => normalizeOptions(o)), + fileHandling: isIgnored ? "ignored" : "transpile", + ignore: ignoreFile || undefined, + babelrc: babelrcFile || undefined, + config: configFile || undefined, + files: chain.files + }; + } + + function babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory) { + if (typeof babelrcRoots === "boolean") return babelrcRoots; + const absoluteRoot = context.root; + + if (babelrcRoots === undefined) { + return pkgData.directories.indexOf(absoluteRoot) !== -1; + } + + let babelrcPatterns = babelrcRoots; + if (!Array.isArray(babelrcPatterns)) babelrcPatterns = [babelrcPatterns]; + babelrcPatterns = babelrcPatterns.map(pat => { + return typeof pat === "string" ? _path().default.resolve(babelrcRootsDirectory, pat) : pat; + }); + + if (babelrcPatterns.length === 1 && babelrcPatterns[0] === absoluteRoot) { + return pkgData.directories.indexOf(absoluteRoot) !== -1; + } + + return babelrcPatterns.some(pat => { + if (typeof pat === "string") { + pat = (0, _patternToRegex.default)(pat, babelrcRootsDirectory); + } + + return pkgData.directories.some(directory => { + return matchPattern(pat, babelrcRootsDirectory, directory, context); + }); + }); + } + + const validateConfigFile = (0, caching.makeWeakCacheSync)(file => ({ + filepath: file.filepath, + dirname: file.dirname, + options: (0, options$1.validate)("configfile", file.options) + })); + const validateBabelrcFile = (0, caching.makeWeakCacheSync)(file => ({ + filepath: file.filepath, + dirname: file.dirname, + options: (0, options$1.validate)("babelrcfile", file.options) + })); + const validateExtendFile = (0, caching.makeWeakCacheSync)(file => ({ + filepath: file.filepath, + dirname: file.dirname, + options: (0, options$1.validate)("extendsfile", file.options) + })); + const loadProgrammaticChain = makeChainWalker({ + root: input => buildRootDescriptors(input, "base", configDescriptors.createCachedDescriptors), + env: (input, envName) => buildEnvDescriptors(input, "base", configDescriptors.createCachedDescriptors, envName), + overrides: (input, index) => buildOverrideDescriptors(input, "base", configDescriptors.createCachedDescriptors, index), + overridesEnv: (input, index, envName) => buildOverrideEnvDescriptors(input, "base", configDescriptors.createCachedDescriptors, index, envName), + createLogger: (input, context, baseLogger) => buildProgrammaticLogger(input, context, baseLogger) + }); + const loadFileChainWalker = makeChainWalker({ + root: file => loadFileDescriptors(file), + env: (file, envName) => loadFileEnvDescriptors(file)(envName), + overrides: (file, index) => loadFileOverridesDescriptors(file)(index), + overridesEnv: (file, index, envName) => loadFileOverridesEnvDescriptors(file)(index)(envName), + createLogger: (file, context, baseLogger) => buildFileLogger(file.filepath, context, baseLogger) + }); + + function* loadFileChain(input, context, files, baseLogger) { + const chain = yield* loadFileChainWalker(input, context, files, baseLogger); + + if (chain) { + chain.files.add(input.filepath); + } + + return chain; + } + + const loadFileDescriptors = (0, caching.makeWeakCacheSync)(file => buildRootDescriptors(file, file.filepath, configDescriptors.createUncachedDescriptors)); + const loadFileEnvDescriptors = (0, caching.makeWeakCacheSync)(file => (0, caching.makeStrongCacheSync)(envName => buildEnvDescriptors(file, file.filepath, configDescriptors.createUncachedDescriptors, envName))); + const loadFileOverridesDescriptors = (0, caching.makeWeakCacheSync)(file => (0, caching.makeStrongCacheSync)(index => buildOverrideDescriptors(file, file.filepath, configDescriptors.createUncachedDescriptors, index))); + const loadFileOverridesEnvDescriptors = (0, caching.makeWeakCacheSync)(file => (0, caching.makeStrongCacheSync)(index => (0, caching.makeStrongCacheSync)(envName => buildOverrideEnvDescriptors(file, file.filepath, configDescriptors.createUncachedDescriptors, index, envName)))); + + function buildFileLogger(filepath, context, baseLogger) { + if (!baseLogger) { + return () => {}; + } + + return baseLogger.configure(context.showConfig, printer$1.ChainFormatter.Config, { + filepath + }); + } + + function buildRootDescriptors({ + dirname, + options + }, alias, descriptors) { + return descriptors(dirname, options, alias); + } + + function buildProgrammaticLogger(_, context, baseLogger) { + var _context$caller; + + if (!baseLogger) { + return () => {}; + } + + return baseLogger.configure(context.showConfig, printer$1.ChainFormatter.Programmatic, { + callerName: (_context$caller = context.caller) == null ? void 0 : _context$caller.name + }); + } + + function buildEnvDescriptors({ + dirname, + options + }, alias, descriptors, envName) { + const opts = options.env && options.env[envName]; + return opts ? descriptors(dirname, opts, `${alias}.env["${envName}"]`) : null; + } + + function buildOverrideDescriptors({ + dirname, + options + }, alias, descriptors, index) { + const opts = options.overrides && options.overrides[index]; + if (!opts) throw new Error("Assertion failure - missing override"); + return descriptors(dirname, opts, `${alias}.overrides[${index}]`); + } + + function buildOverrideEnvDescriptors({ + dirname, + options + }, alias, descriptors, index, envName) { + const override = options.overrides && options.overrides[index]; + if (!override) throw new Error("Assertion failure - missing override"); + const opts = override.env && override.env[envName]; + return opts ? descriptors(dirname, opts, `${alias}.overrides[${index}].env["${envName}"]`) : null; + } + + function makeChainWalker({ + root, + env, + overrides, + overridesEnv, + createLogger + }) { + return function* (input, context, files = new Set(), baseLogger) { + const { + dirname + } = input; + const flattenedConfigs = []; + const rootOpts = root(input); + + if (configIsApplicable(rootOpts, dirname, context)) { + flattenedConfigs.push({ + config: rootOpts, + envName: undefined, + index: undefined + }); + const envOpts = env(input, context.envName); + + if (envOpts && configIsApplicable(envOpts, dirname, context)) { + flattenedConfigs.push({ + config: envOpts, + envName: context.envName, + index: undefined + }); + } + + (rootOpts.options.overrides || []).forEach((_, index) => { + const overrideOps = overrides(input, index); + + if (configIsApplicable(overrideOps, dirname, context)) { + flattenedConfigs.push({ + config: overrideOps, + index, + envName: undefined + }); + const overrideEnvOpts = overridesEnv(input, index, context.envName); + + if (overrideEnvOpts && configIsApplicable(overrideEnvOpts, dirname, context)) { + flattenedConfigs.push({ + config: overrideEnvOpts, + index, + envName: context.envName + }); + } + } + }); + } + + if (flattenedConfigs.some(({ + config: { + options: { + ignore, + only + } + } + }) => shouldIgnore(context, ignore, only, dirname))) { + return null; + } + + const chain = emptyChain(); + const logger = createLogger(input, context, baseLogger); + + for (const { + config, + index, + envName + } of flattenedConfigs) { + if (!(yield* mergeExtendsChain(chain, config.options, dirname, context, files, baseLogger))) { + return null; + } + + logger(config, index, envName); + mergeChainOpts(chain, config); + } + + return chain; + }; + } + + function* mergeExtendsChain(chain, opts, dirname, context, files$1, baseLogger) { + if (opts.extends === undefined) return true; + const file = yield* (0, files.loadConfig)(opts.extends, dirname, context.envName, context.caller); + + if (files$1.has(file)) { + throw new Error(`Configuration cycle detected loading ${file.filepath}.\n` + `File already loaded following the config chain:\n` + Array.from(files$1, file => ` - ${file.filepath}`).join("\n")); + } + + files$1.add(file); + const fileChain = yield* loadFileChain(validateExtendFile(file), context, files$1, baseLogger); + files$1.delete(file); + if (!fileChain) return false; + mergeChain(chain, fileChain); + return true; + } + + function mergeChain(target, source) { + target.options.push(...source.options); + target.plugins.push(...source.plugins); + target.presets.push(...source.presets); + + for (const file of source.files) { + target.files.add(file); + } + + return target; + } + + function mergeChainOpts(target, { + options, + plugins, + presets + }) { + target.options.push(options); + target.plugins.push(...plugins()); + target.presets.push(...presets()); + return target; + } + + function emptyChain() { + return { + options: [], + presets: [], + plugins: [], + files: new Set() + }; + } + + function normalizeOptions(opts) { + const options = Object.assign({}, opts); + delete options.extends; + delete options.env; + delete options.overrides; + delete options.plugins; + delete options.presets; + delete options.passPerPreset; + delete options.ignore; + delete options.only; + delete options.test; + delete options.include; + delete options.exclude; + + if (Object.prototype.hasOwnProperty.call(options, "sourceMap")) { + options.sourceMaps = options.sourceMap; + delete options.sourceMap; + } + + return options; + } + + function dedupDescriptors(items) { + const map = new Map(); + const descriptors = []; + + for (const item of items) { + if (typeof item.value === "function") { + const fnKey = item.value; + let nameMap = map.get(fnKey); + + if (!nameMap) { + nameMap = new Map(); + map.set(fnKey, nameMap); + } + + let desc = nameMap.get(item.name); + + if (!desc) { + desc = { + value: item + }; + descriptors.push(desc); + if (!item.ownPass) nameMap.set(item.name, desc); + } else { + desc.value = item; + } + } else { + descriptors.push({ + value: item + }); + } + } + + return descriptors.reduce((acc, desc) => { + acc.push(desc.value); + return acc; + }, []); + } + + function configIsApplicable({ + options + }, dirname, context) { + return (options.test === undefined || configFieldIsApplicable(context, options.test, dirname)) && (options.include === undefined || configFieldIsApplicable(context, options.include, dirname)) && (options.exclude === undefined || !configFieldIsApplicable(context, options.exclude, dirname)); + } + + function configFieldIsApplicable(context, test, dirname) { + const patterns = Array.isArray(test) ? test : [test]; + return matchesPatterns(context, patterns, dirname); + } + + function shouldIgnore(context, ignore, only, dirname) { + if (ignore && matchesPatterns(context, ignore, dirname)) { + var _context$filename; + + const message = `No config is applied to "${(_context$filename = context.filename) != null ? _context$filename : "(unknown)"}" because it matches one of \`ignore: ${JSON.stringify(ignore)}\` from "${dirname}"`; + debug(message); + + if (context.showConfig) { + console.log(message); + } + + return true; + } + + if (only && !matchesPatterns(context, only, dirname)) { + var _context$filename2; + + const message = `No config is applied to "${(_context$filename2 = context.filename) != null ? _context$filename2 : "(unknown)"}" because it fails to match one of \`only: ${JSON.stringify(only)}\` from "${dirname}"`; + debug(message); + + if (context.showConfig) { + console.log(message); + } + + return true; + } + + return false; + } + + function matchesPatterns(context, patterns, dirname) { + return patterns.some(pattern => matchPattern(pattern, dirname, context.filename, context)); + } + + function matchPattern(pattern, dirname, pathToTest, context) { + if (typeof pattern === "function") { + return !!pattern(pathToTest, { + dirname, + envName: context.envName, + caller: context.caller + }); + } + + if (typeof pathToTest !== "string") { + throw new Error(`Configuration contains string/RegExp pattern, but no filename was passed to Babel`); + } + + if (typeof pattern === "string") { + pattern = (0, _patternToRegex.default)(pattern, dirname); + } + + return pattern.test(pathToTest); + } + }); + + unwrapExports(configChain); + var configChain_1 = configChain.buildPresetChain; + var configChain_2 = configChain.buildRootChain; + var configChain_3 = configChain.buildPresetChainWalker; + + var plugins$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.validatePluginObject = validatePluginObject; + + + + const VALIDATORS = { + name: optionAssertions.assertString, + manipulateOptions: optionAssertions.assertFunction, + pre: optionAssertions.assertFunction, + post: optionAssertions.assertFunction, + inherits: optionAssertions.assertFunction, + visitor: assertVisitorMap, + parserOverride: optionAssertions.assertFunction, + generatorOverride: optionAssertions.assertFunction + }; + + function assertVisitorMap(loc, value) { + const obj = (0, optionAssertions.assertObject)(loc, value); + + if (obj) { + Object.keys(obj).forEach(prop => assertVisitorHandler(prop, obj[prop])); + + if (obj.enter || obj.exit) { + throw new Error(`${(0, optionAssertions.msg)(loc)} cannot contain catch-all "enter" or "exit" handlers. Please target individual nodes.`); + } + } + + return obj; + } + + function assertVisitorHandler(key, value) { + if (value && typeof value === "object") { + Object.keys(value).forEach(handler => { + if (handler !== "enter" && handler !== "exit") { + throw new Error(`.visitor["${key}"] may only have .enter and/or .exit handlers.`); + } + }); + } else if (typeof value !== "function") { + throw new Error(`.visitor["${key}"] must be a function`); + } + + return value; + } + + function validatePluginObject(obj) { + const rootPath = { + type: "root", + source: "plugin" + }; + Object.keys(obj).forEach(key => { + const validator = VALIDATORS[key]; + + if (validator) { + const optLoc = { + type: "option", + name: key, + parent: rootPath + }; + validator(optLoc, obj[key]); + } else { + const invalidPluginPropertyError = new Error(`.${key} is not a valid Plugin property`); + invalidPluginPropertyError.code = "BABEL_UNKNOWN_PLUGIN_PROPERTY"; + throw invalidPluginPropertyError; + } + }); + return obj; + } + }); + + unwrapExports(plugins$1); + var plugins_1$1 = plugins$1.validatePluginObject; + + var partial = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = loadPrivatePartialConfig; + exports.loadPartialConfig = void 0; + + function _path() { + const data = _interopRequireDefault(require$$1); + + _path = function () { + return data; + }; + + return data; + } + + function _gensync() { + const data = _interopRequireDefault(gensync); + + _gensync = function () { + return data; + }; + + return data; + } + + var _plugin = _interopRequireDefault(plugin); + + + + + + + + + + + + + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } + + function* resolveRootMode(rootDir, rootMode) { + switch (rootMode) { + case "root": + return rootDir; + + case "upward-optional": + { + const upwardRootDir = yield* (0, files.findConfigUpwards)(rootDir); + return upwardRootDir === null ? rootDir : upwardRootDir; + } + + case "upward": + { + const upwardRootDir = yield* (0, files.findConfigUpwards)(rootDir); + if (upwardRootDir !== null) return upwardRootDir; + throw Object.assign(new Error(`Babel was run with rootMode:"upward" but a root could not ` + `be found when searching upward from "${rootDir}".\n` + `One of the following config files must be in the directory tree: ` + `"${files.ROOT_CONFIG_FILENAMES.join(", ")}".`), { + code: "BABEL_ROOT_NOT_FOUND", + dirname: rootDir + }); + } + + default: + throw new Error(`Assertion failure - unknown rootMode value.`); + } + } + + function* loadPrivatePartialConfig(inputOpts) { + if (inputOpts != null && (typeof inputOpts !== "object" || Array.isArray(inputOpts))) { + throw new Error("Babel options must be an object, null, or undefined"); + } + + const args = inputOpts ? (0, options$1.validate)("arguments", inputOpts) : {}; + const { + envName = (0, environment.getEnv)(), + cwd = ".", + root: rootDir = ".", + rootMode = "root", + caller, + cloneInputAst = true + } = args; + + const absoluteCwd = _path().default.resolve(cwd); + + const absoluteRootDir = yield* resolveRootMode(_path().default.resolve(absoluteCwd, rootDir), rootMode); + const filename = typeof args.filename === "string" ? _path().default.resolve(cwd, args.filename) : undefined; + const showConfigPath = yield* (0, files.resolveShowConfigPath)(absoluteCwd); + const context = { + filename, + cwd: absoluteCwd, + root: absoluteRootDir, + envName, + caller, + showConfig: showConfigPath === filename + }; + const configChain$1 = yield* (0, configChain.buildRootChain)(args, context); + if (!configChain$1) return null; + const options = {}; + configChain$1.options.forEach(opts => { + (0, util$4.mergeOptions)(options, opts); + }); + options.cloneInputAst = cloneInputAst; + options.babelrc = false; + options.configFile = false; + options.passPerPreset = false; + options.envName = context.envName; + options.cwd = context.cwd; + options.root = context.root; + options.filename = typeof context.filename === "string" ? context.filename : undefined; + options.plugins = configChain$1.plugins.map(descriptor => (0, item.createItemFromDescriptor)(descriptor)); + options.presets = configChain$1.presets.map(descriptor => (0, item.createItemFromDescriptor)(descriptor)); + return { + options, + context, + fileHandling: configChain$1.fileHandling, + ignore: configChain$1.ignore, + babelrc: configChain$1.babelrc, + config: configChain$1.config, + files: configChain$1.files + }; + } + + const loadPartialConfig = (0, _gensync().default)(function* (opts) { + let showIgnoredFiles = false; + + if (typeof opts === "object" && opts !== null && !Array.isArray(opts)) { + var _opts = opts; + ({ + showIgnoredFiles + } = _opts); + opts = _objectWithoutPropertiesLoose(_opts, ["showIgnoredFiles"]); + } + + const result = yield* loadPrivatePartialConfig(opts); + if (!result) return null; + const { + options, + babelrc, + ignore, + config, + fileHandling, + files + } = result; + + if (fileHandling === "ignored" && !showIgnoredFiles) { + return null; + } + + (options.plugins || []).forEach(item => { + if (item.value instanceof _plugin.default) { + throw new Error("Passing cached plugin instances is not supported in " + "babel.loadPartialConfig()"); + } + }); + return new PartialConfig(options, babelrc ? babelrc.filepath : undefined, ignore ? ignore.filepath : undefined, config ? config.filepath : undefined, fileHandling, files); + }); + exports.loadPartialConfig = loadPartialConfig; + + class PartialConfig { + constructor(options, babelrc, ignore, config, fileHandling, files) { + this.options = void 0; + this.babelrc = void 0; + this.babelignore = void 0; + this.config = void 0; + this.fileHandling = void 0; + this.files = void 0; + this.options = options; + this.babelignore = ignore; + this.babelrc = babelrc; + this.config = config; + this.fileHandling = fileHandling; + this.files = files; + Object.freeze(this); + } + + hasFilesystemConfig() { + return this.babelrc !== undefined || this.config !== undefined; + } + + } + + Object.freeze(PartialConfig.prototype); + }); + + unwrapExports(partial); + var partial_1 = partial.loadPartialConfig; + + var full = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = void 0; + + function _gensync() { + const data = _interopRequireDefault(gensync); + + _gensync = function () { + return data; + }; + + return data; + } + + + + + + var context = _interopRequireWildcard(lib$j); + + var _plugin = _interopRequireDefault(plugin); + + + + + + function _traverse() { + const data = _interopRequireDefault(lib$a); + + _traverse = function () { + return data; + }; + + return data; + } + + + + + + + + var _configApi = _interopRequireDefault(configApi); + + var _partial = _interopRequireDefault(partial); + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + var _default = (0, _gensync().default)(function* loadFullConfig(inputOpts) { + const result = yield* (0, _partial.default)(inputOpts); + + if (!result) { + return null; + } + + const { + options, + context, + fileHandling + } = result; + + if (fileHandling === "ignored") { + return null; + } + + const optionDefaults = {}; + const { + plugins, + presets + } = options; + + if (!plugins || !presets) { + throw new Error("Assertion failure - plugins and presets exist"); + } + + const toDescriptor = item$1 => { + const desc = (0, item.getItemDescriptor)(item$1); + + if (!desc) { + throw new Error("Assertion failure - must be config item"); + } + + return desc; + }; + + const presetsDescriptors = presets.map(toDescriptor); + const initialPluginsDescriptors = plugins.map(toDescriptor); + const pluginDescriptorsByPass = [[]]; + const passes = []; + const ignored = yield* enhanceError(context, function* recursePresetDescriptors(rawPresets, pluginDescriptorsPass) { + const presets = []; + + for (let i = 0; i < rawPresets.length; i++) { + const descriptor = rawPresets[i]; + + if (descriptor.options !== false) { + try { + if (descriptor.ownPass) { + presets.push({ + preset: yield* loadPresetDescriptor(descriptor, context), + pass: [] + }); + } else { + presets.unshift({ + preset: yield* loadPresetDescriptor(descriptor, context), + pass: pluginDescriptorsPass + }); + } + } catch (e) { + if (e.code === "BABEL_UNKNOWN_OPTION") { + (0, options$1.checkNoUnwrappedItemOptionPairs)(rawPresets, i, "preset", e); + } + + throw e; + } + } + } + + if (presets.length > 0) { + pluginDescriptorsByPass.splice(1, 0, ...presets.map(o => o.pass).filter(p => p !== pluginDescriptorsPass)); + + for (const { + preset, + pass + } of presets) { + if (!preset) return true; + pass.push(...preset.plugins); + const ignored = yield* recursePresetDescriptors(preset.presets, pass); + if (ignored) return true; + preset.options.forEach(opts => { + (0, util$4.mergeOptions)(optionDefaults, opts); + }); + } + } + })(presetsDescriptors, pluginDescriptorsByPass[0]); + if (ignored) return null; + const opts = optionDefaults; + (0, util$4.mergeOptions)(opts, options); + yield* enhanceError(context, function* loadPluginDescriptors() { + pluginDescriptorsByPass[0].unshift(...initialPluginsDescriptors); + + for (const descs of pluginDescriptorsByPass) { + const pass = []; + passes.push(pass); + + for (let i = 0; i < descs.length; i++) { + const descriptor = descs[i]; + + if (descriptor.options !== false) { + try { + pass.push(yield* loadPluginDescriptor(descriptor, context)); + } catch (e) { + if (e.code === "BABEL_UNKNOWN_PLUGIN_PROPERTY") { + (0, options$1.checkNoUnwrappedItemOptionPairs)(descs, i, "plugin", e); + } + + throw e; + } + } + } + } + })(); + opts.plugins = passes[0]; + opts.presets = passes.slice(1).filter(plugins => plugins.length > 0).map(plugins => ({ + plugins + })); + opts.passPerPreset = opts.presets.length > 0; + return { + options: opts, + passes: passes + }; + }); + + exports.default = _default; + + function enhanceError(context, fn) { + return function* (arg1, arg2) { + try { + return yield* fn(arg1, arg2); + } catch (e) { + if (!/^\[BABEL\]/.test(e.message)) { + e.message = `[BABEL] ${context.filename || "unknown"}: ${e.message}`; + } + + throw e; + } + }; + } + + const loadDescriptor = (0, caching.makeWeakCache)(function* ({ + value, + options, + dirname, + alias + }, cache) { + if (options === false) throw new Error("Assertion failure"); + options = options || {}; + let item = value; + + if (typeof value === "function") { + const api = Object.assign({}, context, (0, _configApi.default)(cache)); + + try { + item = value(api, options, dirname); + } catch (e) { + if (alias) { + e.message += ` (While processing: ${JSON.stringify(alias)})`; + } + + throw e; + } + } + + if (!item || typeof item !== "object") { + throw new Error("Plugin/Preset did not return an object."); + } + + if (typeof item.then === "function") { + yield* []; + throw new Error(`You appear to be using an async plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, ` + `you may need to upgrade your @babel/core version.`); + } + + return { + value: item, + options, + dirname, + alias + }; + }); + + function* loadPluginDescriptor(descriptor, context) { + if (descriptor.value instanceof _plugin.default) { + if (descriptor.options) { + throw new Error("Passed options to an existing Plugin instance will not work."); + } + + return descriptor.value; + } + + return yield* instantiatePlugin(yield* loadDescriptor(descriptor, context), context); + } + + const instantiatePlugin = (0, caching.makeWeakCache)(function* ({ + value, + options, + dirname, + alias + }, cache) { + const pluginObj = (0, plugins$1.validatePluginObject)(value); + const plugin = Object.assign({}, pluginObj); + + if (plugin.visitor) { + plugin.visitor = _traverse().default.explode(Object.assign({}, plugin.visitor)); + } + + if (plugin.inherits) { + const inheritsDescriptor = { + name: undefined, + alias: `${alias}$inherits`, + value: plugin.inherits, + options, + dirname + }; + const inherits = yield* (0, async.forwardAsync)(loadPluginDescriptor, run => { + return cache.invalidate(data => run(inheritsDescriptor, data)); + }); + plugin.pre = chain(inherits.pre, plugin.pre); + plugin.post = chain(inherits.post, plugin.post); + plugin.manipulateOptions = chain(inherits.manipulateOptions, plugin.manipulateOptions); + plugin.visitor = _traverse().default.visitors.merge([inherits.visitor || {}, plugin.visitor || {}]); + } + + return new _plugin.default(plugin, options, alias); + }); + + const validateIfOptionNeedsFilename = (options, descriptor) => { + if (options.test || options.include || options.exclude) { + const formattedPresetName = descriptor.name ? `"${descriptor.name}"` : "/* your preset */"; + throw new Error([`Preset ${formattedPresetName} requires a filename to be set when babel is called directly,`, `\`\`\``, `babel.transform(code, { filename: 'file.ts', presets: [${formattedPresetName}] });`, `\`\`\``, `See https://babeljs.io/docs/en/options#filename for more information.`].join("\n")); + } + }; + + const validatePreset = (preset, context, descriptor) => { + if (!context.filename) { + const { + options + } = preset; + validateIfOptionNeedsFilename(options, descriptor); + + if (options.overrides) { + options.overrides.forEach(overrideOptions => validateIfOptionNeedsFilename(overrideOptions, descriptor)); + } + } + }; + + function* loadPresetDescriptor(descriptor, context) { + const preset = instantiatePreset(yield* loadDescriptor(descriptor, context)); + validatePreset(preset, context, descriptor); + return yield* (0, configChain.buildPresetChain)(preset, context); + } + + const instantiatePreset = (0, caching.makeWeakCacheSync)(({ + value, + dirname, + alias + }) => { + return { + options: (0, options$1.validate)("preset", value), + alias, + dirname + }; + }); + + function chain(a, b) { + const fns = [a, b].filter(Boolean); + if (fns.length <= 1) return fns[0]; + return function (...args) { + for (const fn of fns) { + fn.apply(this, args); + } + }; + } + }); + + unwrapExports(full); + + var config$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + Object.defineProperty(exports, "default", { + enumerable: true, + get: function () { + return _full.default; + } + }); + exports.loadOptionsAsync = exports.loadOptionsSync = exports.loadOptions = exports.loadPartialConfigAsync = exports.loadPartialConfigSync = exports.loadPartialConfig = void 0; + + function _gensync() { + const data = _interopRequireDefault(gensync); + + _gensync = function () { + return data; + }; + + return data; + } + + var _full = _interopRequireDefault(full); + + + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + const loadOptionsRunner = (0, _gensync().default)(function* (opts) { + var _config$options; + + const config = yield* (0, _full.default)(opts); + return (_config$options = config == null ? void 0 : config.options) != null ? _config$options : null; + }); + + const maybeErrback = runner => (opts, callback) => { + if (callback === undefined && typeof opts === "function") { + callback = opts; + opts = undefined; + } + + return callback ? runner.errback(opts, callback) : runner.sync(opts); + }; + + const loadPartialConfig = maybeErrback(partial.loadPartialConfig); + exports.loadPartialConfig = loadPartialConfig; + const loadPartialConfigSync = partial.loadPartialConfig.sync; + exports.loadPartialConfigSync = loadPartialConfigSync; + const loadPartialConfigAsync = partial.loadPartialConfig.async; + exports.loadPartialConfigAsync = loadPartialConfigAsync; + const loadOptions = maybeErrback(loadOptionsRunner); + exports.loadOptions = loadOptions; + const loadOptionsSync = loadOptionsRunner.sync; + exports.loadOptionsSync = loadOptionsSync; + const loadOptionsAsync = loadOptionsRunner.async; + exports.loadOptionsAsync = loadOptionsAsync; + }); + + unwrapExports(config$1); + var config_1 = config$1.loadOptionsAsync; + var config_2 = config$1.loadOptionsSync; + var config_3 = config$1.loadOptions; + var config_4 = config$1.loadPartialConfigAsync; + var config_5 = config$1.loadPartialConfigSync; + var config_6 = config$1.loadPartialConfig; + + var pluginPass = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = void 0; + + class PluginPass { + constructor(file, key, options) { + this._map = new Map(); + this.key = void 0; + this.file = void 0; + this.opts = void 0; + this.cwd = void 0; + this.filename = void 0; + this.key = key; + this.file = file; + this.opts = options || {}; + this.cwd = file.opts.cwd; + this.filename = file.opts.filename; + } + + set(key, val) { + this._map.set(key, val); + } + + get(key) { + return this._map.get(key); + } + + availableHelper(name, versionRange) { + return this.file.availableHelper(name, versionRange); + } + + addHelper(name) { + return this.file.addHelper(name); + } + + addImport() { + return this.file.addImport(); + } + + getModuleName() { + return this.file.getModuleName(); + } + + buildCodeFrameError(node, msg, Error) { + return this.file.buildCodeFrameError(node, msg, Error); + } + + } + + exports.default = PluginPass; + }); + + unwrapExports(pluginPass); + + /** Built-in value references. */ + var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined; + + /** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ + function isFlattenable(value) { + return isArray_1(value) || isArguments_1(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); + } + + var _isFlattenable = isFlattenable; + + /** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ + function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = _isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + _arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; + } + + var _baseFlatten = baseFlatten; + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/; + + /** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ + function isKey(value, object) { + if (isArray_1(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol_1(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + } + + var _isKey = isKey; + + /** Error message constants. */ + var FUNC_ERROR_TEXT = 'Expected a function'; + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || _MapCache); + return memoized; + } + + // Expose `MapCache`. + memoize.Cache = _MapCache; + + var memoize_1 = memoize; + + /** Used as the maximum memoize cache size. */ + var MAX_MEMOIZE_SIZE = 500; + + /** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ + function memoizeCapped(func) { + var result = memoize_1(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; + } + + var _memoizeCapped = memoizeCapped; + + /** Used to match property names within property paths. */ + var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + var stringToPath = _memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + }); + + var _stringToPath = stringToPath; + + /** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ + function castPath(value, object) { + if (isArray_1(value)) { + return value; + } + return _isKey(value, object) ? [value] : _stringToPath(toString_1(value)); + } + + var _castPath = castPath; + + /** Used as references for various `Number` constants. */ + var INFINITY$2 = 1 / 0; + + /** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + function toKey(value) { + if (typeof value == 'string' || isSymbol_1(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY$2) ? '-0' : result; + } + + var _toKey = toKey; + + /** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ + function baseGet(object, path) { + path = _castPath(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[_toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; + } + + var _baseGet = baseGet; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; + + /** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED$2); + return this; + } + + var _setCacheAdd = setCacheAdd; + + /** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ + function setCacheHas(value) { + return this.__data__.has(value); + } + + var _setCacheHas = setCacheHas; + + /** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new _MapCache; + while (++index < length) { + this.add(values[index]); + } + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd; + SetCache.prototype.has = _setCacheHas; + + var _SetCache = SetCache; + + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + var _arraySome = arraySome; + + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key); + } + + var _cacheHas = cacheHas; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Check that cyclic values are equal. + var arrStacked = stack.get(array); + var othStacked = stack.get(other); + if (arrStacked && othStacked) { + return arrStacked == other && othStacked == array; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new _SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!_arraySome(other, function(othValue, othIndex) { + if (!_cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; + } + + var _equalArrays = equalArrays; + + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + + var _mapToArray = mapToArray; + + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + + var _setToArray = setToArray; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$1 = 1, + COMPARE_UNORDERED_FLAG$1 = 2; + + /** `Object#toString` result references. */ + var boolTag$3 = '[object Boolean]', + dateTag$3 = '[object Date]', + errorTag$2 = '[object Error]', + mapTag$5 = '[object Map]', + numberTag$3 = '[object Number]', + regexpTag$4 = '[object RegExp]', + setTag$5 = '[object Set]', + stringTag$3 = '[object String]', + symbolTag$3 = '[object Symbol]'; + + var arrayBufferTag$3 = '[object ArrayBuffer]', + dataViewTag$4 = '[object DataView]'; + + /** Used to convert symbols to primitives and strings. */ + var symbolProto$2 = _Symbol ? _Symbol.prototype : undefined, + symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined; + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag$4: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag$3: + if ((object.byteLength != other.byteLength) || + !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) { + return false; + } + return true; + + case boolTag$3: + case dateTag$3: + case numberTag$3: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq_1(+object, +other); + + case errorTag$2: + return object.name == other.name && object.message == other.message; + + case regexpTag$4: + case stringTag$3: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag$5: + var convert = _mapToArray; + + case setTag$5: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; + convert || (convert = _setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG$1; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag$3: + if (symbolValueOf$1) { + return symbolValueOf$1.call(object) == symbolValueOf$1.call(other); + } + } + return false; + } + + var _equalByTag = equalByTag; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$2 = 1; + + /** Used for built-in method references. */ + var objectProto$e = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$e = objectProto$e.hasOwnProperty; + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, + objProps = _getAllKeys(object), + objLength = objProps.length, + othProps = _getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty$e.call(other, key))) { + return false; + } + } + // Check that cyclic values are equal. + var objStacked = stack.get(object); + var othStacked = stack.get(other); + if (objStacked && othStacked) { + return objStacked == other && othStacked == object; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; + } + + var _equalObjects = equalObjects; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$3 = 1; + + /** `Object#toString` result references. */ + var argsTag$3 = '[object Arguments]', + arrayTag$2 = '[object Array]', + objectTag$4 = '[object Object]'; + + /** Used for built-in method references. */ + var objectProto$f = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty$f = objectProto$f.hasOwnProperty; + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray_1(object), + othIsArr = isArray_1(other), + objTag = objIsArr ? arrayTag$2 : _getTag(object), + othTag = othIsArr ? arrayTag$2 : _getTag(other); + + objTag = objTag == argsTag$3 ? objectTag$4 : objTag; + othTag = othTag == argsTag$3 ? objectTag$4 : othTag; + + var objIsObj = objTag == objectTag$4, + othIsObj = othTag == objectTag$4, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer_1(object)) { + if (!isBuffer_1(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new _Stack); + return (objIsArr || isTypedArray_1(object)) + ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { + var objIsWrapped = objIsObj && hasOwnProperty$f.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty$f.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new _Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new _Stack); + return _equalObjects(object, other, bitmask, customizer, equalFunc, stack); + } + + var _baseIsEqualDeep = baseIsEqualDeep; + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) { + return value !== value && other !== other; + } + return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } + + var _baseIsEqual = baseIsEqual; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$4 = 1, + COMPARE_UNORDERED_FLAG$2 = 2; + + /** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new _Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) + : result + )) { + return false; + } + } + } + return true; + } + + var _baseIsMatch = baseIsMatch; + + /** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ + function isStrictComparable(value) { + return value === value && !isObject_1(value); + } + + var _isStrictComparable = isStrictComparable; + + /** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ + function getMatchData(object) { + var result = keys_1(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, _isStrictComparable(value)]; + } + return result; + } + + var _getMatchData = getMatchData; + + /** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; + } + + var _matchesStrictComparable = matchesStrictComparable; + + /** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatches(source) { + var matchData = _getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return _matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || _baseIsMatch(object, source, matchData); + }; + } + + var _baseMatches = baseMatches; + + /** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : _baseGet(object, path); + return result === undefined ? defaultValue : result; + } + + var get_1 = get; + + /** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHasIn(object, key) { + return object != null && key in Object(object); + } + + var _baseHasIn = baseHasIn; + + /** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ + function hasPath(object, path, hasFunc) { + path = _castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = _toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength_1(length) && _isIndex(key, length) && + (isArray_1(object) || isArguments_1(object)); + } + + var _hasPath = hasPath; + + /** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ + function hasIn(object, path) { + return object != null && _hasPath(object, path, _baseHasIn); + } + + var hasIn_1 = hasIn; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG$5 = 1, + COMPARE_UNORDERED_FLAG$3 = 2; + + /** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatchesProperty(path, srcValue) { + if (_isKey(path) && _isStrictComparable(srcValue)) { + return _matchesStrictComparable(_toKey(path), srcValue); + } + return function(object) { + var objValue = get_1(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn_1(object, path) + : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); + }; + } + + var _baseMatchesProperty = baseMatchesProperty; + + /** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ + function identity(value) { + return value; + } + + var identity_1 = identity; + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + var _baseProperty = baseProperty; + + /** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyDeep(path) { + return function(object) { + return _baseGet(object, path); + }; + } + + var _basePropertyDeep = basePropertyDeep; + + /** + * Creates a function that returns the value at `path` of a given object. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + * @example + * + * var objects = [ + * { 'a': { 'b': 2 } }, + * { 'a': { 'b': 1 } } + * ]; + * + * _.map(objects, _.property('a.b')); + * // => [2, 1] + * + * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); + * // => [1, 2] + */ + function property(path) { + return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path); + } + + var property_1 = property; + + /** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity_1; + } + if (typeof value == 'object') { + return isArray_1(value) + ? _baseMatchesProperty(value[0], value[1]) + : _baseMatches(value); + } + return property_1(value); + } + + var _baseIteratee = baseIteratee; + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + var _createBaseFor = createBaseFor; + + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = _createBaseFor(); + + var _baseFor = baseFor; + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && _baseFor(object, iteratee, keys_1); + } + + var _baseForOwn = baseForOwn; + + /** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike_1(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; + } + + var _createBaseEach = createBaseEach; + + /** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEach = _createBaseEach(_baseForOwn); + + var _baseEach = baseEach; + + /** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike_1(collection) ? Array(collection.length) : []; + + _baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; + } + + var _baseMap = baseMap; + + /** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ + function baseSortBy(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; + } + + var _baseSortBy = baseSortBy; + + /** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ + function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = isSymbol_1(value); + + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = isSymbol_1(other); + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; + } + + var _compareAscending = compareAscending; + + /** + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. + * + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]|string[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. + */ + function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; + + while (++index < length) { + var result = _compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * (order == 'desc' ? -1 : 1); + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; + } + + var _compareMultiple = compareMultiple; + + /** + * The base implementation of `_.orderBy` without param guards. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {string[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. + */ + function baseOrderBy(collection, iteratees, orders) { + if (iteratees.length) { + iteratees = _arrayMap(iteratees, function(iteratee) { + if (isArray_1(iteratee)) { + return function(value) { + return _baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); + } + } + return iteratee; + }); + } else { + iteratees = [identity_1]; + } + + var index = -1; + iteratees = _arrayMap(iteratees, _baseUnary(_baseIteratee)); + + var result = _baseMap(collection, function(value, key, collection) { + var criteria = _arrayMap(iteratees, function(iteratee) { + return iteratee(value); + }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); + + return _baseSortBy(result, function(object, other) { + return _compareMultiple(object, other, orders); + }); + } + + var _baseOrderBy = baseOrderBy; + + /** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ + function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); + } + + var _apply = apply; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeMax$1 = Math.max; + + /** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ + function overRest(func, start, transform) { + start = nativeMax$1(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax$1(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return _apply(func, this, otherArgs); + }; + } + + var _overRest = overRest; + + /** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ + function constant(value) { + return function() { + return value; + }; + } + + var constant_1 = constant; + + /** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var baseSetToString = !_defineProperty ? identity_1 : function(func, string) { + return _defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant_1(string), + 'writable': true + }); + }; + + var _baseSetToString = baseSetToString; + + /** Used to detect hot functions by number of calls within a span of milliseconds. */ + var HOT_COUNT = 800, + HOT_SPAN = 16; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeNow = Date.now; + + /** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ + function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; + } + + var _shortOut = shortOut; + + /** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var setToString = _shortOut(_baseSetToString); + + var _setToString = setToString; + + /** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ + function baseRest(func, start) { + return _setToString(_overRest(func, start, identity_1), func + ''); + } + + var _baseRest = baseRest; + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 30 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, [function(o) { return o.user; }]); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] + */ + var sortBy = _baseRest(function(collection, iteratees) { + if (collection == null) { + return []; + } + var length = iteratees.length; + if (length > 1 && _isIterateeCall(collection, iteratees[0], iteratees[1])) { + iteratees = []; + } else if (length > 2 && _isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { + iteratees = [iteratees[0]]; + } + return _baseOrderBy(collection, _baseFlatten(iteratees, 1), []); + }); + + var sortBy_1 = sortBy; + + var blockHoistPlugin_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = loadBlockHoistPlugin; + + function _sortBy() { + const data = _interopRequireDefault(sortBy_1); + + _sortBy = function () { + return data; + }; + + return data; + } + + var _config = _interopRequireDefault(config$1); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + let LOADED_PLUGIN; + + function loadBlockHoistPlugin() { + if (!LOADED_PLUGIN) { + const config = _config.default.sync({ + babelrc: false, + configFile: false, + plugins: [blockHoistPlugin] + }); + + LOADED_PLUGIN = config ? config.passes[0][0] : undefined; + if (!LOADED_PLUGIN) throw new Error("Assertion failure"); + } + + return LOADED_PLUGIN; + } + + const blockHoistPlugin = { + name: "internal.blockHoist", + visitor: { + Block: { + exit({ + node + }) { + let hasChange = false; + + for (let i = 0; i < node.body.length; i++) { + const bodyNode = node.body[i]; + + if ((bodyNode == null ? void 0 : bodyNode._blockHoist) != null) { + hasChange = true; + break; + } + } + + if (!hasChange) return; + node.body = (0, _sortBy().default)(node.body, function (bodyNode) { + let priority = bodyNode == null ? void 0 : bodyNode._blockHoist; + if (priority == null) priority = 1; + if (priority === true) priority = 2; + return -1 * priority; + }); + } + + } + } + }; + }); + + unwrapExports(blockHoistPlugin_1); + + var normalizeOpts = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = normalizeOptions; + + function _path() { + const data = _interopRequireDefault(require$$1); + + _path = function () { + return data; + }; + + return data; + } + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function normalizeOptions(config) { + const { + filename, + cwd, + filenameRelative = typeof filename === "string" ? _path().default.relative(cwd, filename) : "unknown", + sourceType = "module", + inputSourceMap, + sourceMaps = !!inputSourceMap, + moduleRoot, + sourceRoot = moduleRoot, + sourceFileName = _path().default.basename(filenameRelative), + comments = true, + compact = "auto" + } = config.options; + const opts = config.options; + const options = Object.assign({}, opts, { + parserOpts: Object.assign({ + sourceType: _path().default.extname(filenameRelative) === ".mjs" ? "module" : sourceType, + sourceFileName: filename, + plugins: [] + }, opts.parserOpts), + generatorOpts: Object.assign({ + filename, + auxiliaryCommentBefore: opts.auxiliaryCommentBefore, + auxiliaryCommentAfter: opts.auxiliaryCommentAfter, + retainLines: opts.retainLines, + comments, + shouldPrintComment: opts.shouldPrintComment, + compact, + minified: opts.minified, + sourceMaps, + sourceRoot, + sourceFileName + }, opts.generatorOpts) + }); + + for (const plugins of config.passes) { + for (const plugin of plugins) { + if (plugin.manipulateOptions) { + plugin.manipulateOptions(options, options.parserOpts); + } + } + } + + return options; + } + }); + + unwrapExports(normalizeOpts); + + /** Used to compose bitmasks for cloning. */ + var CLONE_DEEP_FLAG$1 = 1, + CLONE_SYMBOLS_FLAG$2 = 4; + + /** + * This method is like `_.clone` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @returns {*} Returns the deep cloned value. + * @see _.clone + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var deep = _.cloneDeep(objects); + * console.log(deep[0] === objects[0]); + * // => false + */ + function cloneDeep(value) { + return _baseClone(value, CLONE_DEEP_FLAG$1 | CLONE_SYMBOLS_FLAG$2); + } + + var cloneDeep_1$1 = cloneDeep; + + var safeBuffer = createCommonjsModule(function (module, exports) { + /* eslint-disable node/no-deprecated-api */ + + var Buffer = bufferEs6.Buffer; + + // alternative to using Object.keys for old browsers + function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key]; + } + } + if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = bufferEs6; + } else { + // Copy properties from require('buffer') + copyProps(bufferEs6, exports); + exports.Buffer = SafeBuffer; + } + + function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) + } + + // Copy static methods from Buffer + copyProps(Buffer, SafeBuffer); + + SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) + }; + + SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size); + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding); + } else { + buf.fill(fill); + } + } else { + buf.fill(0); + } + return buf + }; + + SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) + }; + + SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return bufferEs6.SlowBuffer(size) + }; + }); + var safeBuffer_1 = safeBuffer.Buffer; + + var convertSourceMap = createCommonjsModule(function (module, exports) { + + + + + Object.defineProperty(exports, 'commentRegex', { + get: function getCommentRegex () { + return /^\s*\/(?:\/|\*)[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/mg; + } + }); + + Object.defineProperty(exports, 'mapFileCommentRegex', { + get: function getMapFileCommentRegex () { + // Matches sourceMappingURL in either // or /* comment styles. + return /(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"`]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/){1}[ \t]*$)/mg; + } + }); + + + function decodeBase64(base64) { + return safeBuffer.Buffer.from(base64, 'base64').toString(); + } + + function stripComment(sm) { + return sm.split(',').pop(); + } + + function readFromFileMap(sm, dir) { + // NOTE: this will only work on the server since it attempts to read the map file + + var r = exports.mapFileCommentRegex.exec(sm); + + // for some odd reason //# .. captures in 1 and /* .. */ in 2 + var filename = r[1] || r[2]; + var filepath = require$$1.resolve(dir, filename); + + try { + return require$$0$1.readFileSync(filepath, 'utf8'); + } catch (e) { + throw new Error('An error occurred while trying to read the map file at ' + filepath + '\n' + e); + } + } + + function Converter (sm, opts) { + opts = opts || {}; + + if (opts.isFileComment) sm = readFromFileMap(sm, opts.commentFileDir); + if (opts.hasComment) sm = stripComment(sm); + if (opts.isEncoded) sm = decodeBase64(sm); + if (opts.isJSON || opts.isEncoded) sm = JSON.parse(sm); + + this.sourcemap = sm; + } + + Converter.prototype.toJSON = function (space) { + return JSON.stringify(this.sourcemap, null, space); + }; + + Converter.prototype.toBase64 = function () { + var json = this.toJSON(); + return safeBuffer.Buffer.from(json, 'utf8').toString('base64'); + }; + + Converter.prototype.toComment = function (options) { + var base64 = this.toBase64(); + var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64; + return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; + }; + + // returns copy instead of original + Converter.prototype.toObject = function () { + return JSON.parse(this.toJSON()); + }; + + Converter.prototype.addProperty = function (key, value) { + if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead'); + return this.setProperty(key, value); + }; + + Converter.prototype.setProperty = function (key, value) { + this.sourcemap[key] = value; + return this; + }; + + Converter.prototype.getProperty = function (key) { + return this.sourcemap[key]; + }; + + exports.fromObject = function (obj) { + return new Converter(obj); + }; + + exports.fromJSON = function (json) { + return new Converter(json, { isJSON: true }); + }; + + exports.fromBase64 = function (base64) { + return new Converter(base64, { isEncoded: true }); + }; + + exports.fromComment = function (comment) { + comment = comment + .replace(/^\/\*/g, '//') + .replace(/\*\/$/g, ''); + + return new Converter(comment, { isEncoded: true, hasComment: true }); + }; + + exports.fromMapFileComment = function (comment, dir) { + return new Converter(comment, { commentFileDir: dir, isFileComment: true, isJSON: true }); + }; + + // Finds last sourcemap comment in file or returns null if none was found + exports.fromSource = function (content) { + var m = content.match(exports.commentRegex); + return m ? exports.fromComment(m.pop()) : null; + }; + + // Finds last sourcemap comment in file or returns null if none was found + exports.fromMapFileSource = function (content, dir) { + var m = content.match(exports.mapFileCommentRegex); + return m ? exports.fromMapFileComment(m.pop(), dir) : null; + }; + + exports.removeComments = function (src) { + return src.replace(exports.commentRegex, ''); + }; + + exports.removeMapFileComments = function (src) { + return src.replace(exports.mapFileCommentRegex, ''); + }; + + exports.generateMapFileComment = function (file, options) { + var data = 'sourceMappingURL=' + file; + return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; + }; + }); + var convertSourceMap_1 = convertSourceMap.fromObject; + var convertSourceMap_2 = convertSourceMap.fromJSON; + var convertSourceMap_3 = convertSourceMap.fromBase64; + var convertSourceMap_4 = convertSourceMap.fromComment; + var convertSourceMap_5 = convertSourceMap.fromMapFileComment; + var convertSourceMap_6 = convertSourceMap.fromSource; + var convertSourceMap_7 = convertSourceMap.fromMapFileSource; + var convertSourceMap_8 = convertSourceMap.removeComments; + var convertSourceMap_9 = convertSourceMap.removeMapFileComments; + var convertSourceMap_10 = convertSourceMap.generateMapFileComment; + + var missingPluginHelper = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = generateMissingPluginMessage; + const pluginNameMap = { + classProperties: { + syntax: { + name: "@babel/plugin-syntax-class-properties", + url: "https://git.io/vb4yQ" + }, + transform: { + name: "@babel/plugin-proposal-class-properties", + url: "https://git.io/vb4SL" + } + }, + classPrivateProperties: { + syntax: { + name: "@babel/plugin-syntax-class-properties", + url: "https://git.io/vb4yQ" + }, + transform: { + name: "@babel/plugin-proposal-class-properties", + url: "https://git.io/vb4SL" + } + }, + classPrivateMethods: { + syntax: { + name: "@babel/plugin-syntax-class-properties", + url: "https://git.io/vb4yQ" + }, + transform: { + name: "@babel/plugin-proposal-private-methods", + url: "https://git.io/JvpRG" + } + }, + classStaticBlock: { + syntax: { + name: "@babel/plugin-syntax-class-static-block", + url: "https://git.io/JTLB6" + }, + transform: { + name: "@babel/plugin-proposal-class-static-block", + url: "https://git.io/JTLBP" + } + }, + decimal: { + syntax: { + name: "@babel/plugin-syntax-decimal", + url: "https://git.io/JfKOH" + } + }, + decorators: { + syntax: { + name: "@babel/plugin-syntax-decorators", + url: "https://git.io/vb4y9" + }, + transform: { + name: "@babel/plugin-proposal-decorators", + url: "https://git.io/vb4ST" + } + }, + doExpressions: { + syntax: { + name: "@babel/plugin-syntax-do-expressions", + url: "https://git.io/vb4yh" + }, + transform: { + name: "@babel/plugin-proposal-do-expressions", + url: "https://git.io/vb4S3" + } + }, + dynamicImport: { + syntax: { + name: "@babel/plugin-syntax-dynamic-import", + url: "https://git.io/vb4Sv" + } + }, + exportDefaultFrom: { + syntax: { + name: "@babel/plugin-syntax-export-default-from", + url: "https://git.io/vb4SO" + }, + transform: { + name: "@babel/plugin-proposal-export-default-from", + url: "https://git.io/vb4yH" + } + }, + exportNamespaceFrom: { + syntax: { + name: "@babel/plugin-syntax-export-namespace-from", + url: "https://git.io/vb4Sf" + }, + transform: { + name: "@babel/plugin-proposal-export-namespace-from", + url: "https://git.io/vb4SG" + } + }, + flow: { + syntax: { + name: "@babel/plugin-syntax-flow", + url: "https://git.io/vb4yb" + }, + transform: { + name: "@babel/preset-flow", + url: "https://git.io/JfeDn" + } + }, + functionBind: { + syntax: { + name: "@babel/plugin-syntax-function-bind", + url: "https://git.io/vb4y7" + }, + transform: { + name: "@babel/plugin-proposal-function-bind", + url: "https://git.io/vb4St" + } + }, + functionSent: { + syntax: { + name: "@babel/plugin-syntax-function-sent", + url: "https://git.io/vb4yN" + }, + transform: { + name: "@babel/plugin-proposal-function-sent", + url: "https://git.io/vb4SZ" + } + }, + importMeta: { + syntax: { + name: "@babel/plugin-syntax-import-meta", + url: "https://git.io/vbKK6" + } + }, + jsx: { + syntax: { + name: "@babel/plugin-syntax-jsx", + url: "https://git.io/vb4yA" + }, + transform: { + name: "@babel/preset-react", + url: "https://git.io/JfeDR" + } + }, + importAssertions: { + syntax: { + name: "@babel/plugin-syntax-import-assertions", + url: "https://git.io/JUbkv" + } + }, + moduleStringNames: { + syntax: { + name: "@babel/plugin-syntax-module-string-names", + url: "https://git.io/JTL8G" + } + }, + numericSeparator: { + syntax: { + name: "@babel/plugin-syntax-numeric-separator", + url: "https://git.io/vb4Sq" + }, + transform: { + name: "@babel/plugin-proposal-numeric-separator", + url: "https://git.io/vb4yS" + } + }, + optionalChaining: { + syntax: { + name: "@babel/plugin-syntax-optional-chaining", + url: "https://git.io/vb4Sc" + }, + transform: { + name: "@babel/plugin-proposal-optional-chaining", + url: "https://git.io/vb4Sk" + } + }, + pipelineOperator: { + syntax: { + name: "@babel/plugin-syntax-pipeline-operator", + url: "https://git.io/vb4yj" + }, + transform: { + name: "@babel/plugin-proposal-pipeline-operator", + url: "https://git.io/vb4SU" + } + }, + privateIn: { + syntax: { + name: "@babel/plugin-syntax-private-property-in-object", + url: "https://git.io/JfK3q" + }, + transform: { + name: "@babel/plugin-proposal-private-property-in-object", + url: "https://git.io/JfK3O" + } + }, + recordAndTuple: { + syntax: { + name: "@babel/plugin-syntax-record-and-tuple", + url: "https://git.io/JvKp3" + } + }, + throwExpressions: { + syntax: { + name: "@babel/plugin-syntax-throw-expressions", + url: "https://git.io/vb4SJ" + }, + transform: { + name: "@babel/plugin-proposal-throw-expressions", + url: "https://git.io/vb4yF" + } + }, + typescript: { + syntax: { + name: "@babel/plugin-syntax-typescript", + url: "https://git.io/vb4SC" + }, + transform: { + name: "@babel/preset-typescript", + url: "https://git.io/JfeDz" + } + }, + asyncGenerators: { + syntax: { + name: "@babel/plugin-syntax-async-generators", + url: "https://git.io/vb4SY" + }, + transform: { + name: "@babel/plugin-proposal-async-generator-functions", + url: "https://git.io/vb4yp" + } + }, + logicalAssignment: { + syntax: { + name: "@babel/plugin-syntax-logical-assignment-operators", + url: "https://git.io/vAlBp" + }, + transform: { + name: "@babel/plugin-proposal-logical-assignment-operators", + url: "https://git.io/vAlRe" + } + }, + nullishCoalescingOperator: { + syntax: { + name: "@babel/plugin-syntax-nullish-coalescing-operator", + url: "https://git.io/vb4yx" + }, + transform: { + name: "@babel/plugin-proposal-nullish-coalescing-operator", + url: "https://git.io/vb4Se" + } + }, + objectRestSpread: { + syntax: { + name: "@babel/plugin-syntax-object-rest-spread", + url: "https://git.io/vb4y5" + }, + transform: { + name: "@babel/plugin-proposal-object-rest-spread", + url: "https://git.io/vb4Ss" + } + }, + optionalCatchBinding: { + syntax: { + name: "@babel/plugin-syntax-optional-catch-binding", + url: "https://git.io/vb4Sn" + }, + transform: { + name: "@babel/plugin-proposal-optional-catch-binding", + url: "https://git.io/vb4SI" + } + } + }; + pluginNameMap.privateIn.syntax = pluginNameMap.privateIn.transform; + + const getNameURLCombination = ({ + name, + url + }) => `${name} (${url})`; + + function generateMissingPluginMessage(missingPluginName, loc, codeFrame) { + let helpMessage = `Support for the experimental syntax '${missingPluginName}' isn't currently enabled ` + `(${loc.line}:${loc.column + 1}):\n\n` + codeFrame; + const pluginInfo = pluginNameMap[missingPluginName]; + + if (pluginInfo) { + const { + syntax: syntaxPlugin, + transform: transformPlugin + } = pluginInfo; + + if (syntaxPlugin) { + const syntaxPluginInfo = getNameURLCombination(syntaxPlugin); + + if (transformPlugin) { + const transformPluginInfo = getNameURLCombination(transformPlugin); + const sectionType = transformPlugin.name.startsWith("@babel/plugin") ? "plugins" : "presets"; + helpMessage += `\n\nAdd ${transformPluginInfo} to the '${sectionType}' section of your Babel config to enable transformation. +If you want to leave it as-is, add ${syntaxPluginInfo} to the 'plugins' section to enable parsing.`; + } else { + helpMessage += `\n\nAdd ${syntaxPluginInfo} to the 'plugins' section of your Babel config ` + `to enable parsing.`; + } + } + } + + return helpMessage; + } + }); + + unwrapExports(missingPluginHelper); + + var parser_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = parser; + + function _parser() { + const data = lib$6; + + _parser = function () { + return data; + }; + + return data; + } + + function _codeFrame() { + const data = lib$5; + + _codeFrame = function () { + return data; + }; + + return data; + } + + var _missingPluginHelper = _interopRequireDefault(missingPluginHelper); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function* parser(pluginPasses, { + parserOpts, + highlightCode = true, + filename = "unknown" + }, code) { + try { + const results = []; + + for (const plugins of pluginPasses) { + for (const plugin of plugins) { + const { + parserOverride + } = plugin; + + if (parserOverride) { + const ast = parserOverride(code, parserOpts, _parser().parse); + if (ast !== undefined) results.push(ast); + } + } + } + + if (results.length === 0) { + return (0, _parser().parse)(code, parserOpts); + } else if (results.length === 1) { + yield* []; + + if (typeof results[0].then === "function") { + throw new Error(`You appear to be using an async parser plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`); + } + + return results[0]; + } + + throw new Error("More than one plugin attempted to override parsing."); + } catch (err) { + if (err.code === "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED") { + err.message += "\nConsider renaming the file to '.mjs', or setting sourceType:module " + "or sourceType:unambiguous in your Babel config for this file."; + } + + const { + loc, + missingPlugin + } = err; + + if (loc) { + const codeFrame = (0, _codeFrame().codeFrameColumns)(code, { + start: { + line: loc.line, + column: loc.column + 1 + } + }, { + highlightCode + }); + + if (missingPlugin) { + err.message = `${filename}: ` + (0, _missingPluginHelper.default)(missingPlugin[0], loc, codeFrame); + } else { + err.message = `${filename}: ${err.message}\n\n` + codeFrame; + } + + err.code = "BABEL_PARSE_ERROR"; + } + + throw err; + } + } + }); + + unwrapExports(parser_1); + + var normalizeFile_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = normalizeFile; + + function _fs() { + const data = _interopRequireDefault(require$$0$1); + + _fs = function () { + return data; + }; + + return data; + } + + function _path() { + const data = _interopRequireDefault(require$$1); + + _path = function () { + return data; + }; + + return data; + } + + function _debug() { + const data = _interopRequireDefault(src); + + _debug = function () { + return data; + }; + + return data; + } + + function _cloneDeep() { + const data = _interopRequireDefault(cloneDeep_1$1); + + _cloneDeep = function () { + return data; + }; + + return data; + } + + function t() { + const data = _interopRequireWildcard(lib$1); + + t = function () { + return data; + }; + + return data; + } + + function _convertSourceMap() { + const data = _interopRequireDefault(convertSourceMap); + + _convertSourceMap = function () { + return data; + }; + + return data; + } + + var _file = _interopRequireDefault(file); + + var _parser = _interopRequireDefault(parser_1); + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + const debug = (0, _debug().default)("babel:transform:file"); + const LARGE_INPUT_SOURCEMAP_THRESHOLD = 1000000; + + function* normalizeFile(pluginPasses, options, code, ast) { + code = `${code || ""}`; + + if (ast) { + if (ast.type === "Program") { + ast = t().file(ast, [], []); + } else if (ast.type !== "File") { + throw new Error("AST root must be a Program or File node"); + } + + const { + cloneInputAst + } = options; + + if (cloneInputAst) { + ast = (0, _cloneDeep().default)(ast); + } + } else { + ast = yield* (0, _parser.default)(pluginPasses, options, code); + } + + let inputMap = null; + + if (options.inputSourceMap !== false) { + if (typeof options.inputSourceMap === "object") { + inputMap = _convertSourceMap().default.fromObject(options.inputSourceMap); + } + + if (!inputMap) { + const lastComment = extractComments(INLINE_SOURCEMAP_REGEX, ast); + + if (lastComment) { + try { + inputMap = _convertSourceMap().default.fromComment(lastComment); + } catch (err) { + debug("discarding unknown inline input sourcemap", err); + } + } + } + + if (!inputMap) { + const lastComment = extractComments(EXTERNAL_SOURCEMAP_REGEX, ast); + + if (typeof options.filename === "string" && lastComment) { + try { + const match = EXTERNAL_SOURCEMAP_REGEX.exec(lastComment); + + const inputMapContent = _fs().default.readFileSync(_path().default.resolve(_path().default.dirname(options.filename), match[1])); + + if (inputMapContent.length > LARGE_INPUT_SOURCEMAP_THRESHOLD) { + debug("skip merging input map > 1 MB"); + } else { + inputMap = _convertSourceMap().default.fromJSON(inputMapContent); + } + } catch (err) { + debug("discarding unknown file input sourcemap", err); + } + } else if (lastComment) { + debug("discarding un-loadable file input sourcemap"); + } + } + } + + return new _file.default(options, { + code, + ast, + inputMap + }); + } + + const INLINE_SOURCEMAP_REGEX = /^[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/; + const EXTERNAL_SOURCEMAP_REGEX = /^[@#][ \t]+sourceMappingURL=([^\s'"`]+)[ \t]*$/; + + function extractCommentsFromList(regex, comments, lastComment) { + if (comments) { + comments = comments.filter(({ + value + }) => { + if (regex.test(value)) { + lastComment = value; + return false; + } + + return true; + }); + } + + return [comments, lastComment]; + } + + function extractComments(regex, ast) { + let lastComment = null; + t().traverseFast(ast, node => { + [node.leadingComments, lastComment] = extractCommentsFromList(regex, node.leadingComments, lastComment); + [node.innerComments, lastComment] = extractCommentsFromList(regex, node.innerComments, lastComment); + [node.trailingComments, lastComment] = extractCommentsFromList(regex, node.trailingComments, lastComment); + }); + return lastComment; + } + }); + + unwrapExports(normalizeFile_1); + + var mergeMap = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = mergeSourceMap; + + function _sourceMap() { + const data = _interopRequireDefault(sourceMap); + + _sourceMap = function () { + return data; + }; + + return data; + } + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function mergeSourceMap(inputMap, map) { + const input = buildMappingData(inputMap); + const output = buildMappingData(map); + const mergedGenerator = new (_sourceMap().default.SourceMapGenerator)(); + + for (const { + source + } of input.sources) { + if (typeof source.content === "string") { + mergedGenerator.setSourceContent(source.path, source.content); + } + } + + if (output.sources.length === 1) { + const defaultSource = output.sources[0]; + const insertedMappings = new Map(); + eachInputGeneratedRange(input, (generated, original, source) => { + eachOverlappingGeneratedOutputRange(defaultSource, generated, item => { + const key = makeMappingKey(item); + if (insertedMappings.has(key)) return; + insertedMappings.set(key, item); + mergedGenerator.addMapping({ + source: source.path, + original: { + line: original.line, + column: original.columnStart + }, + generated: { + line: item.line, + column: item.columnStart + }, + name: original.name + }); + }); + }); + + for (const item of insertedMappings.values()) { + if (item.columnEnd === Infinity) { + continue; + } + + const clearItem = { + line: item.line, + columnStart: item.columnEnd + }; + const key = makeMappingKey(clearItem); + + if (insertedMappings.has(key)) { + continue; + } + + mergedGenerator.addMapping({ + generated: { + line: clearItem.line, + column: clearItem.columnStart + } + }); + } + } + + const result = mergedGenerator.toJSON(); + + if (typeof input.sourceRoot === "string") { + result.sourceRoot = input.sourceRoot; + } + + return result; + } + + function makeMappingKey(item) { + return `${item.line}/${item.columnStart}`; + } + + function eachOverlappingGeneratedOutputRange(outputFile, inputGeneratedRange, callback) { + const overlappingOriginal = filterApplicableOriginalRanges(outputFile, inputGeneratedRange); + + for (const { + generated + } of overlappingOriginal) { + for (const item of generated) { + callback(item); + } + } + } + + function filterApplicableOriginalRanges({ + mappings + }, { + line, + columnStart, + columnEnd + }) { + return filterSortedArray(mappings, ({ + original: outOriginal + }) => { + if (line > outOriginal.line) return -1; + if (line < outOriginal.line) return 1; + if (columnStart >= outOriginal.columnEnd) return -1; + if (columnEnd <= outOriginal.columnStart) return 1; + return 0; + }); + } + + function eachInputGeneratedRange(map, callback) { + for (const { + source, + mappings + } of map.sources) { + for (const { + original, + generated + } of mappings) { + for (const item of generated) { + callback(item, original, source); + } + } + } + } + + function buildMappingData(map) { + const consumer = new (_sourceMap().default.SourceMapConsumer)(Object.assign({}, map, { + sourceRoot: null + })); + const sources = new Map(); + const mappings = new Map(); + let last = null; + consumer.computeColumnSpans(); + consumer.eachMapping(m => { + if (m.originalLine === null) return; + let source = sources.get(m.source); + + if (!source) { + source = { + path: m.source, + content: consumer.sourceContentFor(m.source, true) + }; + sources.set(m.source, source); + } + + let sourceData = mappings.get(source); + + if (!sourceData) { + sourceData = { + source, + mappings: [] + }; + mappings.set(source, sourceData); + } + + const obj = { + line: m.originalLine, + columnStart: m.originalColumn, + columnEnd: Infinity, + name: m.name + }; + + if (last && last.source === source && last.mapping.line === m.originalLine) { + last.mapping.columnEnd = m.originalColumn; + } + + last = { + source, + mapping: obj + }; + sourceData.mappings.push({ + original: obj, + generated: consumer.allGeneratedPositionsFor({ + source: m.source, + line: m.originalLine, + column: m.originalColumn + }).map(item => ({ + line: item.line, + columnStart: item.column, + columnEnd: item.lastColumn + 1 + })) + }); + }, null, _sourceMap().default.SourceMapConsumer.ORIGINAL_ORDER); + return { + file: map.file, + sourceRoot: map.sourceRoot, + sources: Array.from(mappings.values()) + }; + } + + function findInsertionLocation(array, callback) { + let left = 0; + let right = array.length; + + while (left < right) { + const mid = Math.floor((left + right) / 2); + const item = array[mid]; + const result = callback(item); + + if (result === 0) { + left = mid; + break; + } + + if (result >= 0) { + right = mid; + } else { + left = mid + 1; + } + } + + let i = left; + + if (i < array.length) { + while (i >= 0 && callback(array[i]) >= 0) { + i--; + } + + return i + 1; + } + + return i; + } + + function filterSortedArray(array, callback) { + const start = findInsertionLocation(array, callback); + const results = []; + + for (let i = start; i < array.length && callback(array[i]) === 0; i++) { + results.push(array[i]); + } + + return results; + } + }); + + unwrapExports(mergeMap); + + var generate = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = generateCode; + + function _convertSourceMap() { + const data = _interopRequireDefault(convertSourceMap); + + _convertSourceMap = function () { + return data; + }; + + return data; + } + + function _generator() { + const data = _interopRequireDefault(lib$3); + + _generator = function () { + return data; + }; + + return data; + } + + var _mergeMap = _interopRequireDefault(mergeMap); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function generateCode(pluginPasses, file) { + const { + opts, + ast, + code, + inputMap + } = file; + const results = []; + + for (const plugins of pluginPasses) { + for (const plugin of plugins) { + const { + generatorOverride + } = plugin; + + if (generatorOverride) { + const result = generatorOverride(ast, opts.generatorOpts, code, _generator().default); + if (result !== undefined) results.push(result); + } + } + } + + let result; + + if (results.length === 0) { + result = (0, _generator().default)(ast, opts.generatorOpts, code); + } else if (results.length === 1) { + result = results[0]; + + if (typeof result.then === "function") { + throw new Error(`You appear to be using an async codegen plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, ` + `you may need to upgrade your @babel/core version.`); + } + } else { + throw new Error("More than one plugin attempted to override codegen."); + } + + let { + code: outputCode, + map: outputMap + } = result; + + if (outputMap && inputMap) { + outputMap = (0, _mergeMap.default)(inputMap.toObject(), outputMap); + } + + if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") { + outputCode += "\n" + _convertSourceMap().default.fromObject(outputMap).toComment(); + } + + if (opts.sourceMaps === "inline") { + outputMap = null; + } + + return { + outputCode, + outputMap + }; + } + }); + + unwrapExports(generate); + + var transformation = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.run = run; + + function _traverse() { + const data = _interopRequireDefault(lib$a); + + _traverse = function () { + return data; + }; + + return data; + } + + var _pluginPass = _interopRequireDefault(pluginPass); + + var _blockHoistPlugin = _interopRequireDefault(blockHoistPlugin_1); + + var _normalizeOpts = _interopRequireDefault(normalizeOpts); + + var _normalizeFile = _interopRequireDefault(normalizeFile_1); + + var _generate = _interopRequireDefault(generate); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function* run(config, code, ast) { + const file = yield* (0, _normalizeFile.default)(config.passes, (0, _normalizeOpts.default)(config), code, ast); + const opts = file.opts; + + try { + yield* transformFile(file, config.passes); + } catch (e) { + var _opts$filename; + + e.message = `${(_opts$filename = opts.filename) != null ? _opts$filename : "unknown"}: ${e.message}`; + + if (!e.code) { + e.code = "BABEL_TRANSFORM_ERROR"; + } + + throw e; + } + + let outputCode, outputMap; + + try { + if (opts.code !== false) { + ({ + outputCode, + outputMap + } = (0, _generate.default)(config.passes, file)); + } + } catch (e) { + var _opts$filename2; + + e.message = `${(_opts$filename2 = opts.filename) != null ? _opts$filename2 : "unknown"}: ${e.message}`; + + if (!e.code) { + e.code = "BABEL_GENERATE_ERROR"; + } + + throw e; + } + + return { + metadata: file.metadata, + options: opts, + ast: opts.ast === true ? file.ast : null, + code: outputCode === undefined ? null : outputCode, + map: outputMap === undefined ? null : outputMap, + sourceType: file.ast.program.sourceType + }; + } + + function* transformFile(file, pluginPasses) { + for (const pluginPairs of pluginPasses) { + const passPairs = []; + const passes = []; + const visitors = []; + + for (const plugin of pluginPairs.concat([(0, _blockHoistPlugin.default)()])) { + const pass = new _pluginPass.default(file, plugin.key, plugin.options); + passPairs.push([plugin, pass]); + passes.push(pass); + visitors.push(plugin.visitor); + } + + for (const [plugin, pass] of passPairs) { + const fn = plugin.pre; + + if (fn) { + const result = fn.call(pass, file); + yield* []; + + if (isThenable(result)) { + throw new Error(`You appear to be using an plugin with an async .pre, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`); + } + } + } + + const visitor = _traverse().default.visitors.merge(visitors, passes, file.opts.wrapPluginVisitorMethod); + + (0, _traverse().default)(file.ast, visitor, file.scope); + + for (const [plugin, pass] of passPairs) { + const fn = plugin.post; + + if (fn) { + const result = fn.call(pass, file); + yield* []; + + if (isThenable(result)) { + throw new Error(`You appear to be using an plugin with an async .post, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`); + } + } + } + } + } + + function isThenable(val) { + return !!val && (typeof val === "object" || typeof val === "function") && !!val.then && typeof val.then === "function"; + } + }); + + unwrapExports(transformation); + var transformation_1 = transformation.run; + + var transform_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.transformAsync = exports.transformSync = exports.transform = void 0; + + function _gensync() { + const data = _interopRequireDefault(gensync); + + _gensync = function () { + return data; + }; + + return data; + } + + var _config = _interopRequireDefault(config$1); + + + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + const transformRunner = (0, _gensync().default)(function* transform(code, opts) { + const config = yield* (0, _config.default)(opts); + if (config === null) return null; + return yield* (0, transformation.run)(config, code); + }); + + const transform = function transform(code, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = undefined; + } + + if (callback === undefined) return transformRunner.sync(code, opts); + transformRunner.errback(code, opts, callback); + }; + + exports.transform = transform; + const transformSync = transformRunner.sync; + exports.transformSync = transformSync; + const transformAsync = transformRunner.async; + exports.transformAsync = transformAsync; + }); + + unwrapExports(transform_1); + var transform_2 = transform_1.transformAsync; + var transform_3 = transform_1.transformSync; + var transform_4 = transform_1.transform; + + var transformFile_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.transformFileAsync = exports.transformFileSync = exports.transformFile = void 0; + + function _gensync() { + const data = _interopRequireDefault(gensync); + + _gensync = function () { + return data; + }; + + return data; + } + + var _config = _interopRequireDefault(config$1); + + + + var fs$1 = _interopRequireWildcard(fs); + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + const transformFileRunner = (0, _gensync().default)(function* (filename, opts) { + const options = Object.assign({}, opts, { + filename + }); + const config = yield* (0, _config.default)(options); + if (config === null) return null; + const code = yield* fs$1.readFile(filename, "utf8"); + return yield* (0, transformation.run)(config, code); + }); + const transformFile = transformFileRunner.errback; + exports.transformFile = transformFile; + const transformFileSync = transformFileRunner.sync; + exports.transformFileSync = transformFileSync; + const transformFileAsync = transformFileRunner.async; + exports.transformFileAsync = transformFileAsync; + }); + + unwrapExports(transformFile_1); + var transformFile_2 = transformFile_1.transformFileAsync; + var transformFile_3 = transformFile_1.transformFileSync; + var transformFile_4 = transformFile_1.transformFile; + + var transformAst = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.transformFromAstAsync = exports.transformFromAstSync = exports.transformFromAst = void 0; + + function _gensync() { + const data = _interopRequireDefault(gensync); + + _gensync = function () { + return data; + }; + + return data; + } + + var _config = _interopRequireDefault(config$1); + + + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + const transformFromAstRunner = (0, _gensync().default)(function* (ast, code, opts) { + const config = yield* (0, _config.default)(opts); + if (config === null) return null; + if (!ast) throw new Error("No AST given"); + return yield* (0, transformation.run)(config, code, ast); + }); + + const transformFromAst = function transformFromAst(ast, code, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = undefined; + } + + if (callback === undefined) { + return transformFromAstRunner.sync(ast, code, opts); + } + + transformFromAstRunner.errback(ast, code, opts, callback); + }; + + exports.transformFromAst = transformFromAst; + const transformFromAstSync = transformFromAstRunner.sync; + exports.transformFromAstSync = transformFromAstSync; + const transformFromAstAsync = transformFromAstRunner.async; + exports.transformFromAstAsync = transformFromAstAsync; + }); + + unwrapExports(transformAst); + var transformAst_1 = transformAst.transformFromAstAsync; + var transformAst_2 = transformAst.transformFromAstSync; + var transformAst_3 = transformAst.transformFromAst; + + var parse_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.parseAsync = exports.parseSync = exports.parse = void 0; + + function _gensync() { + const data = _interopRequireDefault(gensync); + + _gensync = function () { + return data; + }; + + return data; + } + + var _config = _interopRequireDefault(config$1); + + var _parser = _interopRequireDefault(parser_1); + + var _normalizeOpts = _interopRequireDefault(normalizeOpts); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + const parseRunner = (0, _gensync().default)(function* parse(code, opts) { + const config = yield* (0, _config.default)(opts); + + if (config === null) { + return null; + } + + return yield* (0, _parser.default)(config.passes, (0, _normalizeOpts.default)(config), code); + }); + + const parse = function parse(code, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = undefined; + } + + if (callback === undefined) return parseRunner.sync(code, opts); + parseRunner.errback(code, opts, callback); + }; + + exports.parse = parse; + const parseSync = parseRunner.sync; + exports.parseSync = parseSync; + const parseAsync = parseRunner.async; + exports.parseAsync = parseAsync; + }); + + unwrapExports(parse_1); + var parse_2 = parse_1.parseAsync; + var parse_3 = parse_1.parseSync; + var parse_4 = parse_1.parse; + + var _package$3 = getCjsExportFromNamespace(_package$2); + + var lib$j = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.Plugin = Plugin; + Object.defineProperty(exports, "File", { + enumerable: true, + get: function () { + return _file.default; + } + }); + Object.defineProperty(exports, "buildExternalHelpers", { + enumerable: true, + get: function () { + return _buildExternalHelpers.default; + } + }); + Object.defineProperty(exports, "resolvePlugin", { + enumerable: true, + get: function () { + return files.resolvePlugin; + } + }); + Object.defineProperty(exports, "resolvePreset", { + enumerable: true, + get: function () { + return files.resolvePreset; + } + }); + Object.defineProperty(exports, "version", { + enumerable: true, + get: function () { + return _package$3.version; + } + }); + Object.defineProperty(exports, "getEnv", { + enumerable: true, + get: function () { + return environment.getEnv; + } + }); + Object.defineProperty(exports, "tokTypes", { + enumerable: true, + get: function () { + return _parser().tokTypes; + } + }); + Object.defineProperty(exports, "traverse", { + enumerable: true, + get: function () { + return _traverse().default; + } + }); + Object.defineProperty(exports, "template", { + enumerable: true, + get: function () { + return _template().default; + } + }); + Object.defineProperty(exports, "createConfigItem", { + enumerable: true, + get: function () { + return item.createConfigItem; + } + }); + Object.defineProperty(exports, "loadPartialConfig", { + enumerable: true, + get: function () { + return config$1.loadPartialConfig; + } + }); + Object.defineProperty(exports, "loadPartialConfigSync", { + enumerable: true, + get: function () { + return config$1.loadPartialConfigSync; + } + }); + Object.defineProperty(exports, "loadPartialConfigAsync", { + enumerable: true, + get: function () { + return config$1.loadPartialConfigAsync; + } + }); + Object.defineProperty(exports, "loadOptions", { + enumerable: true, + get: function () { + return config$1.loadOptions; + } + }); + Object.defineProperty(exports, "loadOptionsSync", { + enumerable: true, + get: function () { + return config$1.loadOptionsSync; + } + }); + Object.defineProperty(exports, "loadOptionsAsync", { + enumerable: true, + get: function () { + return config$1.loadOptionsAsync; + } + }); + Object.defineProperty(exports, "transform", { + enumerable: true, + get: function () { + return transform_1.transform; + } + }); + Object.defineProperty(exports, "transformSync", { + enumerable: true, + get: function () { + return transform_1.transformSync; + } + }); + Object.defineProperty(exports, "transformAsync", { + enumerable: true, + get: function () { + return transform_1.transformAsync; + } + }); + Object.defineProperty(exports, "transformFile", { + enumerable: true, + get: function () { + return transformFile_1.transformFile; + } + }); + Object.defineProperty(exports, "transformFileSync", { + enumerable: true, + get: function () { + return transformFile_1.transformFileSync; + } + }); + Object.defineProperty(exports, "transformFileAsync", { + enumerable: true, + get: function () { + return transformFile_1.transformFileAsync; + } + }); + Object.defineProperty(exports, "transformFromAst", { + enumerable: true, + get: function () { + return transformAst.transformFromAst; + } + }); + Object.defineProperty(exports, "transformFromAstSync", { + enumerable: true, + get: function () { + return transformAst.transformFromAstSync; + } + }); + Object.defineProperty(exports, "transformFromAstAsync", { + enumerable: true, + get: function () { + return transformAst.transformFromAstAsync; + } + }); + Object.defineProperty(exports, "parse", { + enumerable: true, + get: function () { + return parse_1.parse; + } + }); + Object.defineProperty(exports, "parseSync", { + enumerable: true, + get: function () { + return parse_1.parseSync; + } + }); + Object.defineProperty(exports, "parseAsync", { + enumerable: true, + get: function () { + return parse_1.parseAsync; + } + }); + exports.types = exports.OptionManager = exports.DEFAULT_EXTENSIONS = void 0; + + var _file = _interopRequireDefault(file); + + var _buildExternalHelpers = _interopRequireDefault(buildExternalHelpers); + + + + + + + + function _types() { + const data = _interopRequireWildcard(lib$1); + + _types = function () { + return data; + }; + + return data; + } + + Object.defineProperty(exports, "types", { + enumerable: true, + get: function () { + return _types(); + } + }); + + function _parser() { + const data = lib$6; + + _parser = function () { + return data; + }; + + return data; + } + + function _traverse() { + const data = _interopRequireDefault(lib$a); + + _traverse = function () { + return data; + }; + + return data; + } + + function _template() { + const data = _interopRequireDefault(lib$8); + + _template = function () { + return data; + }; + + return data; + } + + + + + + + + + + + + + + function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + + function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + const DEFAULT_EXTENSIONS = Object.freeze([".js", ".jsx", ".es6", ".es", ".mjs"]); + exports.DEFAULT_EXTENSIONS = DEFAULT_EXTENSIONS; + + class OptionManager { + init(opts) { + return (0, config$1.loadOptions)(opts); + } + + } + + exports.OptionManager = OptionManager; + + function Plugin(alias) { + throw new Error(`The (${alias}) Babel 5 plugin is being run with an unsupported Babel version.`); + } + }); + + unwrapExports(lib$j); + var lib_1$b = lib$j.Plugin; + var lib_2$7 = lib$j.types; + var lib_3$5 = lib$j.OptionManager; + var lib_4$4 = lib$j.DEFAULT_EXTENSIONS; + + var debugFunc; + var phase = 'default'; + var namespace = ''; + + var newDebug = function newDebug() { + debugFunc = namespace ? src("fetch-mock:".concat(phase, ":").concat(namespace)) : src("fetch-mock:".concat(phase)); + }; + + var newDebugSandbox = function newDebugSandbox(ns) { + return src("fetch-mock:".concat(phase, ":").concat(ns)); + }; + + newDebug(); + var debug_1 = { + debug: function debug() { + debugFunc.apply(void 0, arguments); + }, + setDebugNamespace: function setDebugNamespace(str) { + namespace = str; + newDebug(); + }, + setDebugPhase: function setDebugPhase(str) { + phase = str || 'default'; + newDebug(); + }, + getDebug: function getDebug(namespace) { + return newDebugSandbox(namespace); + } + }; + + var debug = debug_1.debug, + setDebugPhase = debug_1.setDebugPhase; + + var FetchMock = {}; + + FetchMock.mock = function () { + setDebugPhase('setup'); + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + if (args.length) { + this.addRoute(args); + } + + return this._mock(); + }; + + FetchMock.addRoute = function (uncompiledRoute) { + var _this = this; + + debug('Adding route', uncompiledRoute); + var route = this.compileRoute(uncompiledRoute); + var clashes = this.routes.filter(function (_ref) { + var identifier = _ref.identifier, + method = _ref.method; + var isMatch = typeof identifier === 'function' ? identifier === route.identifier : String(identifier) === String(route.identifier); + return isMatch && (!method || !route.method || method === route.method); + }); + + if (this.getOption('overwriteRoutes', route) === false || !clashes.length) { + this._uncompiledRoutes.push(uncompiledRoute); + + return this.routes.push(route); + } + + if (this.getOption('overwriteRoutes', route) === true) { + clashes.forEach(function (clash) { + var index = _this.routes.indexOf(clash); + + _this._uncompiledRoutes.splice(index, 1, uncompiledRoute); + + _this.routes.splice(index, 1, route); + }); + return this.routes; + } + + if (clashes.length) { + throw new Error('fetch-mock: Adding route with same name or matcher as existing route. See `overwriteRoutes` option.'); + } + + this._uncompiledRoutes.push(uncompiledRoute); + + this.routes.push(route); + }; + + FetchMock._mock = function () { + if (!this.isSandbox) { + // Do this here rather than in the constructor to ensure it's scoped to the test + this.realFetch = this.realFetch || this.global.fetch; + this.global.fetch = this.fetchHandler; + } + + setDebugPhase(); + return this; + }; + + FetchMock["catch"] = function (response) { + if (this.fallbackResponse) { + console.warn('calling fetchMock.catch() twice - are you sure you want to overwrite the previous fallback response'); // eslint-disable-line + } + + this.fallbackResponse = response || 'ok'; + return this._mock(); + }; + + FetchMock.spy = function (route) { + // even though ._mock() is called by .mock() and .catch() we still need to + // call it here otherwise .getNativeFetch() won't be able to use the reference + // to .realFetch that ._mock() sets up + this._mock(); + + return route ? this.mock(route, this.getNativeFetch()) : this["catch"](this.getNativeFetch()); + }; + + var defineShorthand = function defineShorthand(methodName, underlyingMethod, shorthandOptions) { + FetchMock[methodName] = function (matcher, response, options) { + return this[underlyingMethod](matcher, response, Object.assign(options || {}, shorthandOptions)); + }; + }; + + var defineGreedyShorthand = function defineGreedyShorthand(methodName, underlyingMethod) { + FetchMock[methodName] = function (response, options) { + return this[underlyingMethod]({}, response, options); + }; + }; + + defineShorthand('sticky', 'mock', { + sticky: true + }); + defineShorthand('once', 'mock', { + repeat: 1 + }); + defineGreedyShorthand('any', 'mock'); + defineGreedyShorthand('anyOnce', 'once'); + ['get', 'post', 'put', 'delete', 'head', 'patch'].forEach(function (method) { + defineShorthand(method, 'mock', { + method: method + }); + defineShorthand("".concat(method, "Once"), 'once', { + method: method + }); + defineGreedyShorthand("".concat(method, "Any"), method); + defineGreedyShorthand("".concat(method, "AnyOnce"), "".concat(method, "Once")); + }); + + var mochaAsyncHookWorkaround = function mochaAsyncHookWorkaround(options) { + // HACK workaround for this https://github.com/mochajs/mocha/issues/4280 + // Note that it doesn't matter that we call it _before_ carrying out all + // the things resetBehavior does as everything in there is synchronous + if (typeof options === 'function') { + console.warn("Deprecated: Passing fetch-mock reset methods\ndirectly in as handlers for before/after test runner hooks.\nWrap in an arrow function instead e.g. `() => fetchMock.restore()`"); + options(); + } + }; + + var getRouteRemover = function getRouteRemover(_ref2) { + var removeStickyRoutes = _ref2.sticky; + return function (routes) { + return removeStickyRoutes ? [] : routes.filter(function (_ref3) { + var sticky = _ref3.sticky; + return sticky; + }); + }; + }; + + FetchMock.resetBehavior = function () { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + mochaAsyncHookWorkaround(options); + var removeRoutes = getRouteRemover(options); + this.routes = removeRoutes(this.routes); + this._uncompiledRoutes = removeRoutes(this._uncompiledRoutes); + + if (this.realFetch && !this.routes.length) { + this.global.fetch = this.realFetch; + this.realFetch = undefined; + } + + this.fallbackResponse = undefined; + return this; + }; + + FetchMock.resetHistory = function () { + this._calls = []; + this._holdingPromises = []; + this.routes.forEach(function (route) { + return route.reset && route.reset(); + }); + return this; + }; + + FetchMock.restore = FetchMock.reset = function (options) { + this.resetBehavior(options); + this.resetHistory(); + return this; + }; + + var setUpAndTearDown = FetchMock; + + var interopRequireDefault = createCommonjsModule(function (module) { + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + "default": obj + }; + } + + module.exports = _interopRequireDefault; + }); + + unwrapExports(interopRequireDefault); + + function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; + } + + var arrayWithHoles = _arrayWithHoles; + + function _iterableToArrayLimit(arr, i) { + if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; + } + + var iterableToArrayLimit = _iterableToArrayLimit; + + function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + + for (var i = 0, arr2 = new Array(len); i < len; i++) { + arr2[i] = arr[i]; + } + + return arr2; + } + + var arrayLikeToArray = _arrayLikeToArray; + + function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); + } + + var unsupportedIterableToArray = _unsupportedIterableToArray; + + function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + var nonIterableRest = _nonIterableRest; + + function _slicedToArray(arr, i) { + return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); + } + + var slicedToArray = _slicedToArray; + + var runtime_1 = createCommonjsModule(function (module) { + /** + * Copyright (c) 2014-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + var runtime = (function (exports) { + + var Op = Object.prototype; + var hasOwn = Op.hasOwnProperty; + var undefined$1; // More compressible than void 0. + var $Symbol = typeof Symbol === "function" ? Symbol : {}; + var iteratorSymbol = $Symbol.iterator || "@@iterator"; + var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; + var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + + function define(obj, key, value) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + return obj[key]; + } + try { + // IE 8 has a broken Object.defineProperty that only works on DOM objects. + define({}, ""); + } catch (err) { + define = function(obj, key, value) { + return obj[key] = value; + }; + } + + function wrap(innerFn, outerFn, self, tryLocsList) { + // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; + var generator = Object.create(protoGenerator.prototype); + var context = new Context(tryLocsList || []); + + // The ._invoke method unifies the implementations of the .next, + // .throw, and .return methods. + generator._invoke = makeInvokeMethod(innerFn, self, context); + + return generator; + } + exports.wrap = wrap; + + // Try/catch helper to minimize deoptimizations. Returns a completion + // record like context.tryEntries[i].completion. This interface could + // have been (and was previously) designed to take a closure to be + // invoked without arguments, but in all the cases we care about we + // already have an existing method we want to call, so there's no need + // to create a new function object. We can even get away with assuming + // the method takes exactly one argument, since that happens to be true + // in every case, so we don't have to touch the arguments object. The + // only additional allocation required is the completion record, which + // has a stable shape and so hopefully should be cheap to allocate. + function tryCatch(fn, obj, arg) { + try { + return { type: "normal", arg: fn.call(obj, arg) }; + } catch (err) { + return { type: "throw", arg: err }; + } + } + + var GenStateSuspendedStart = "suspendedStart"; + var GenStateSuspendedYield = "suspendedYield"; + var GenStateExecuting = "executing"; + var GenStateCompleted = "completed"; + + // Returning this object from the innerFn has the same effect as + // breaking out of the dispatch switch statement. + var ContinueSentinel = {}; + + // Dummy constructor functions that we use as the .constructor and + // .constructor.prototype properties for functions that return Generator + // objects. For full spec compliance, you may wish to configure your + // minifier not to mangle the names of these two functions. + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + + // This is a polyfill for %IteratorPrototype% for environments that + // don't natively support it. + var IteratorPrototype = {}; + IteratorPrototype[iteratorSymbol] = function () { + return this; + }; + + var getProto = Object.getPrototypeOf; + var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); + if (NativeIteratorPrototype && + NativeIteratorPrototype !== Op && + hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { + // This environment has a native %IteratorPrototype%; use it instead + // of the polyfill. + IteratorPrototype = NativeIteratorPrototype; + } + + var Gp = GeneratorFunctionPrototype.prototype = + Generator.prototype = Object.create(IteratorPrototype); + GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; + GeneratorFunctionPrototype.constructor = GeneratorFunction; + GeneratorFunction.displayName = define( + GeneratorFunctionPrototype, + toStringTagSymbol, + "GeneratorFunction" + ); + + // Helper for defining the .next, .throw, and .return methods of the + // Iterator interface in terms of a single ._invoke method. + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function(method) { + define(prototype, method, function(arg) { + return this._invoke(method, arg); + }); + }); + } + + exports.isGeneratorFunction = function(genFun) { + var ctor = typeof genFun === "function" && genFun.constructor; + return ctor + ? ctor === GeneratorFunction || + // For the native GeneratorFunction constructor, the best we can + // do is to check its .name property. + (ctor.displayName || ctor.name) === "GeneratorFunction" + : false; + }; + + exports.mark = function(genFun) { + if (Object.setPrototypeOf) { + Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); + } else { + genFun.__proto__ = GeneratorFunctionPrototype; + define(genFun, toStringTagSymbol, "GeneratorFunction"); + } + genFun.prototype = Object.create(Gp); + return genFun; + }; + + // Within the body of any async function, `await x` is transformed to + // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test + // `hasOwn.call(value, "__await")` to determine if the yielded value is + // meant to be awaited. + exports.awrap = function(arg) { + return { __await: arg }; + }; + + function AsyncIterator(generator, PromiseImpl) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + if (record.type === "throw") { + reject(record.arg); + } else { + var result = record.arg; + var value = result.value; + if (value && + typeof value === "object" && + hasOwn.call(value, "__await")) { + return PromiseImpl.resolve(value.__await).then(function(value) { + invoke("next", value, resolve, reject); + }, function(err) { + invoke("throw", err, resolve, reject); + }); + } + + return PromiseImpl.resolve(value).then(function(unwrapped) { + // When a yielded Promise is resolved, its final value becomes + // the .value of the Promise<{value,done}> result for the + // current iteration. + result.value = unwrapped; + resolve(result); + }, function(error) { + // If a rejected Promise was yielded, throw the rejection back + // into the async generator function so it can be handled there. + return invoke("throw", error, resolve, reject); + }); + } + } + + var previousPromise; + + function enqueue(method, arg) { + function callInvokeWithMethodAndArg() { + return new PromiseImpl(function(resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } + + return previousPromise = + // If enqueue has been called before, then we want to wait until + // all previous Promises have been resolved before calling invoke, + // so that results are always delivered in the correct order. If + // enqueue has not been called before, then it is important to + // call invoke immediately, without waiting on a callback to fire, + // so that the async generator function has the opportunity to do + // any necessary setup in a predictable way. This predictability + // is why the Promise constructor synchronously invokes its + // executor callback, and why async functions synchronously + // execute code before the first await. Since we implement simple + // async functions in terms of async generators, it is especially + // important to get this right, even though it requires care. + previousPromise ? previousPromise.then( + callInvokeWithMethodAndArg, + // Avoid propagating failures to Promises returned by later + // invocations of the iterator. + callInvokeWithMethodAndArg + ) : callInvokeWithMethodAndArg(); + } + + // Define the unified helper method that is used to implement .next, + // .throw, and .return (see defineIteratorMethods). + this._invoke = enqueue; + } + + defineIteratorMethods(AsyncIterator.prototype); + AsyncIterator.prototype[asyncIteratorSymbol] = function () { + return this; + }; + exports.AsyncIterator = AsyncIterator; + + // Note that simple async functions are implemented on top of + // AsyncIterator objects; they just return a Promise for the value of + // the final result produced by the iterator. + exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) { + if (PromiseImpl === void 0) PromiseImpl = Promise; + + var iter = new AsyncIterator( + wrap(innerFn, outerFn, self, tryLocsList), + PromiseImpl + ); + + return exports.isGeneratorFunction(outerFn) + ? iter // If outerFn is a generator, return the full iterator. + : iter.next().then(function(result) { + return result.done ? result.value : iter.next(); + }); + }; + + function makeInvokeMethod(innerFn, self, context) { + var state = GenStateSuspendedStart; + + return function invoke(method, arg) { + if (state === GenStateExecuting) { + throw new Error("Generator is already running"); + } + + if (state === GenStateCompleted) { + if (method === "throw") { + throw arg; + } + + // Be forgiving, per 25.3.3.3.3 of the spec: + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume + return doneResult(); + } + + context.method = method; + context.arg = arg; + + while (true) { + var delegate = context.delegate; + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } + + if (context.method === "next") { + // Setting context._sent for legacy support of Babel's + // function.sent implementation. + context.sent = context._sent = context.arg; + + } else if (context.method === "throw") { + if (state === GenStateSuspendedStart) { + state = GenStateCompleted; + throw context.arg; + } + + context.dispatchException(context.arg); + + } else if (context.method === "return") { + context.abrupt("return", context.arg); + } + + state = GenStateExecuting; + + var record = tryCatch(innerFn, self, context); + if (record.type === "normal") { + // If an exception is thrown from innerFn, we leave state === + // GenStateExecuting and loop back for another invocation. + state = context.done + ? GenStateCompleted + : GenStateSuspendedYield; + + if (record.arg === ContinueSentinel) { + continue; + } + + return { + value: record.arg, + done: context.done + }; + + } else if (record.type === "throw") { + state = GenStateCompleted; + // Dispatch the exception by looping back around to the + // context.dispatchException(context.arg) call above. + context.method = "throw"; + context.arg = record.arg; + } + } + }; + } + + // Call delegate.iterator[context.method](context.arg) and handle the + // result, either by returning a { value, done } result from the + // delegate iterator, or by modifying context.method and context.arg, + // setting context.delegate to null, and returning the ContinueSentinel. + function maybeInvokeDelegate(delegate, context) { + var method = delegate.iterator[context.method]; + if (method === undefined$1) { + // A .throw or .return when the delegate iterator has no .throw + // method always terminates the yield* loop. + context.delegate = null; + + if (context.method === "throw") { + // Note: ["return"] must be used for ES3 parsing compatibility. + if (delegate.iterator["return"]) { + // If the delegate iterator has a return method, give it a + // chance to clean up. + context.method = "return"; + context.arg = undefined$1; + maybeInvokeDelegate(delegate, context); + + if (context.method === "throw") { + // If maybeInvokeDelegate(context) changed context.method from + // "return" to "throw", let that override the TypeError below. + return ContinueSentinel; + } + } + + context.method = "throw"; + context.arg = new TypeError( + "The iterator does not provide a 'throw' method"); + } + + return ContinueSentinel; + } + + var record = tryCatch(method, delegate.iterator, context.arg); + + if (record.type === "throw") { + context.method = "throw"; + context.arg = record.arg; + context.delegate = null; + return ContinueSentinel; + } + + var info = record.arg; + + if (! info) { + context.method = "throw"; + context.arg = new TypeError("iterator result is not an object"); + context.delegate = null; + return ContinueSentinel; + } + + if (info.done) { + // Assign the result of the finished delegate to the temporary + // variable specified by delegate.resultName (see delegateYield). + context[delegate.resultName] = info.value; + + // Resume execution at the desired location (see delegateYield). + context.next = delegate.nextLoc; + + // If context.method was "throw" but the delegate handled the + // exception, let the outer generator proceed normally. If + // context.method was "next", forget context.arg since it has been + // "consumed" by the delegate iterator. If context.method was + // "return", allow the original .return call to continue in the + // outer generator. + if (context.method !== "return") { + context.method = "next"; + context.arg = undefined$1; + } + + } else { + // Re-yield the result returned by the delegate method. + return info; + } + + // The delegate iterator is finished, so forget it and continue with + // the outer generator. + context.delegate = null; + return ContinueSentinel; + } + + // Define Generator.prototype.{next,throw,return} in terms of the + // unified ._invoke helper method. + defineIteratorMethods(Gp); + + define(Gp, toStringTagSymbol, "Generator"); + + // A Generator should always return itself as the iterator object when the + // @@iterator function is called on it. Some browsers' implementations of the + // iterator prototype chain incorrectly implement this, causing the Generator + // object to not be returned from this call. This ensures that doesn't happen. + // See https://github.com/facebook/regenerator/issues/274 for more details. + Gp[iteratorSymbol] = function() { + return this; + }; + + Gp.toString = function() { + return "[object Generator]"; + }; + + function pushTryEntry(locs) { + var entry = { tryLoc: locs[0] }; + + if (1 in locs) { + entry.catchLoc = locs[1]; + } + + if (2 in locs) { + entry.finallyLoc = locs[2]; + entry.afterLoc = locs[3]; + } + + this.tryEntries.push(entry); + } + + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal"; + delete record.arg; + entry.completion = record; + } + + function Context(tryLocsList) { + // The root entry object (effectively a try statement without a catch + // or a finally block) gives us a place to store values thrown from + // locations where there is no enclosing try statement. + this.tryEntries = [{ tryLoc: "root" }]; + tryLocsList.forEach(pushTryEntry, this); + this.reset(true); + } + + exports.keys = function(object) { + var keys = []; + for (var key in object) { + keys.push(key); + } + keys.reverse(); + + // Rather than returning an object with a next method, we keep + // things simple and return the next function itself. + return function next() { + while (keys.length) { + var key = keys.pop(); + if (key in object) { + next.value = key; + next.done = false; + return next; + } + } + + // To avoid creating an additional object, we just hang the .value + // and .done properties off the next function object itself. This + // also ensures that the minifier will not anonymize the function. + next.done = true; + return next; + }; + }; + + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) { + return iteratorMethod.call(iterable); + } + + if (typeof iterable.next === "function") { + return iterable; + } + + if (!isNaN(iterable.length)) { + var i = -1, next = function next() { + while (++i < iterable.length) { + if (hasOwn.call(iterable, i)) { + next.value = iterable[i]; + next.done = false; + return next; + } + } + + next.value = undefined$1; + next.done = true; + + return next; + }; + + return next.next = next; + } + } + + // Return an iterator with no values. + return { next: doneResult }; + } + exports.values = values; + + function doneResult() { + return { value: undefined$1, done: true }; + } + + Context.prototype = { + constructor: Context, + + reset: function(skipTempReset) { + this.prev = 0; + this.next = 0; + // Resetting context._sent for legacy support of Babel's + // function.sent implementation. + this.sent = this._sent = undefined$1; + this.done = false; + this.delegate = null; + + this.method = "next"; + this.arg = undefined$1; + + this.tryEntries.forEach(resetTryEntry); + + if (!skipTempReset) { + for (var name in this) { + // Not sure about the optimal order of these conditions: + if (name.charAt(0) === "t" && + hasOwn.call(this, name) && + !isNaN(+name.slice(1))) { + this[name] = undefined$1; + } + } + } + }, + + stop: function() { + this.done = true; + + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; + if (rootRecord.type === "throw") { + throw rootRecord.arg; + } + + return this.rval; + }, + + dispatchException: function(exception) { + if (this.done) { + throw exception; + } + + var context = this; + function handle(loc, caught) { + record.type = "throw"; + record.arg = exception; + context.next = loc; + + if (caught) { + // If the dispatched exception was caught by a catch block, + // then let that catch block handle the exception normally. + context.method = "next"; + context.arg = undefined$1; + } + + return !! caught; + } + + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + var record = entry.completion; + + if (entry.tryLoc === "root") { + // Exception thrown outside of any try block that could handle + // it, so set the completion value of the entire function to + // throw the exception. + return handle("end"); + } + + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"); + var hasFinally = hasOwn.call(entry, "finallyLoc"); + + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } else if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else if (hasCatch) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } + + } else if (hasFinally) { + if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else { + throw new Error("try statement without catch or finally"); + } + } + } + }, + + abrupt: function(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && + hasOwn.call(entry, "finallyLoc") && + this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } + + if (finallyEntry && + (type === "break" || + type === "continue") && + finallyEntry.tryLoc <= arg && + arg <= finallyEntry.finallyLoc) { + // Ignore the finally entry if control is not jumping to a + // location outside the try/catch block. + finallyEntry = null; + } + + var record = finallyEntry ? finallyEntry.completion : {}; + record.type = type; + record.arg = arg; + + if (finallyEntry) { + this.method = "next"; + this.next = finallyEntry.finallyLoc; + return ContinueSentinel; + } + + return this.complete(record); + }, + + complete: function(record, afterLoc) { + if (record.type === "throw") { + throw record.arg; + } + + if (record.type === "break" || + record.type === "continue") { + this.next = record.arg; + } else if (record.type === "return") { + this.rval = this.arg = record.arg; + this.method = "return"; + this.next = "end"; + } else if (record.type === "normal" && afterLoc) { + this.next = afterLoc; + } + + return ContinueSentinel; + }, + + finish: function(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) { + this.complete(entry.completion, entry.afterLoc); + resetTryEntry(entry); + return ContinueSentinel; + } + } + }, + + "catch": function(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if (record.type === "throw") { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } + + // The context.catch method must only be called with a location + // argument that corresponds to a known catch block. + throw new Error("illegal catch attempt"); + }, + + delegateYield: function(iterable, resultName, nextLoc) { + this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }; + + if (this.method === "next") { + // Deliberately forget the last sent value so that we don't + // accidentally pass it on to the delegate. + this.arg = undefined$1; + } + + return ContinueSentinel; + } + }; + + // Regardless of whether this script is executing as a CommonJS module + // or not, return the runtime object so that we can declare the variable + // regeneratorRuntime in the outer scope, which allows this module to be + // injected easily by `bin/regenerator --include-runtime script.js`. + return exports; + + }( + // If this script is executing as a CommonJS module, use module.exports + // as the regeneratorRuntime namespace. Otherwise create a new empty + // object. Either way, the resulting object will be used to initialize + // the regeneratorRuntime variable at the top of this file. + module.exports + )); + + try { + regeneratorRuntime = runtime; + } catch (accidentalStrictMode) { + // This module should not be running in strict mode, so the above + // assignment should always work unless something is misconfigured. Just + // in case runtime.js accidentally runs in strict mode, we can escape + // strict mode using a global Function call. This could conceivably fail + // if a Content Security Policy forbids using Function, but in that case + // the proper solution is to fix the accidental strict mode problem. If + // you've misconfigured your bundler to force strict mode and applied a + // CSP to forbid Function, and you're not willing to fix either of those + // problems, please detail your unique predicament in a GitHub issue. + Function("r", "regeneratorRuntime = r")(runtime); + } + }); + + var regenerator = runtime_1; + + function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; + } + + if (info.done) { + resolve(value); + } else { + Promise.resolve(value).then(_next, _throw); + } + } + + function _asyncToGenerator(fn) { + return function () { + var self = this, + args = arguments; + return new Promise(function (resolve, reject) { + var gen = fn.apply(self, args); + + function _next(value) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); + } + + function _throw(err) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); + } + + _next(undefined); + }); + }; + } + + var asyncToGenerator = _asyncToGenerator; + + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + + var classCallCheck = _classCallCheck; + + function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return self; + } + + var assertThisInitialized = _assertThisInitialized; + + var setPrototypeOf = createCommonjsModule(function (module) { + function _setPrototypeOf(o, p) { + module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + + return _setPrototypeOf(o, p); + } + + module.exports = _setPrototypeOf; + }); + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + if (superClass) setPrototypeOf(subClass, superClass); + } + + var inherits$2 = _inherits; + + var _typeof_1 = createCommonjsModule(function (module) { + function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + module.exports = _typeof = function _typeof(obj) { + return typeof obj; + }; + } else { + module.exports = _typeof = function _typeof(obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); + } + + module.exports = _typeof; + }); + + function _possibleConstructorReturn(self, call) { + if (call && (_typeof_1(call) === "object" || typeof call === "function")) { + return call; + } + + return assertThisInitialized(self); + } + + var possibleConstructorReturn = _possibleConstructorReturn; + + var getPrototypeOf = createCommonjsModule(function (module) { + function _getPrototypeOf(o) { + module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); + } + + module.exports = _getPrototypeOf; + }); + + function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf("[native code]") !== -1; + } + + var isNativeFunction = _isNativeFunction; + + function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + + try { + Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); + return true; + } catch (e) { + return false; + } + } + + var isNativeReflectConstruct = _isNativeReflectConstruct; + + var construct = createCommonjsModule(function (module) { + function _construct(Parent, args, Class) { + if (isNativeReflectConstruct()) { + module.exports = _construct = Reflect.construct; + } else { + module.exports = _construct = function _construct(Parent, args, Class) { + var a = [null]; + a.push.apply(a, args); + var Constructor = Function.bind.apply(Parent, a); + var instance = new Constructor(); + if (Class) setPrototypeOf(instance, Class.prototype); + return instance; + }; + } + + return _construct.apply(null, arguments); + } + + module.exports = _construct; + }); + + var wrapNativeSuper = createCommonjsModule(function (module) { + function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? new Map() : undefined; + + module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) { + if (Class === null || !isNativeFunction(Class)) return Class; + + if (typeof Class !== "function") { + throw new TypeError("Super expression must either be null or a function"); + } + + if (typeof _cache !== "undefined") { + if (_cache.has(Class)) return _cache.get(Class); + + _cache.set(Class, Wrapper); + } + + function Wrapper() { + return construct(Class, arguments, getPrototypeOf(this).constructor); + } + + Wrapper.prototype = Object.create(Class.prototype, { + constructor: { + value: Wrapper, + enumerable: false, + writable: true, + configurable: true + } + }); + return setPrototypeOf(Wrapper, Class); + }; + + return _wrapNativeSuper(Class); + } + + module.exports = _wrapNativeSuper; + }); + + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } + + var createClass = _createClass; + + var _typeof2 = interopRequireDefault(_typeof_1); + + var _classCallCheck2 = interopRequireDefault(classCallCheck); + + var _createClass2 = interopRequireDefault(createClass); + + var getDebug = debug_1.getDebug; + + var responseConfigProps = ['body', 'headers', 'throws', 'status', 'redirectUrl']; + + var ResponseBuilder = /*#__PURE__*/function () { + function ResponseBuilder(options) { + (0, _classCallCheck2["default"])(this, ResponseBuilder); + this.debug = getDebug('ResponseBuilder()'); + this.debug('Response builder created with options', options); + Object.assign(this, options); + } + + (0, _createClass2["default"])(ResponseBuilder, [{ + key: "exec", + value: function exec() { + this.debug('building response'); + this.normalizeResponseConfig(); + this.constructFetchOpts(); + this.constructResponseBody(); + var realResponse = new this.fetchMock.config.Response(this.body, this.options); + var proxyResponse = this.buildObservableResponse(realResponse); + return [realResponse, proxyResponse]; + } + }, { + key: "sendAsObject", + value: function sendAsObject() { + var _this = this; + + if (responseConfigProps.some(function (prop) { + return _this.responseConfig[prop]; + })) { + if (Object.keys(this.responseConfig).every(function (key) { + return responseConfigProps.includes(key); + })) { + return false; + } else { + return true; + } + } else { + return true; + } + } + }, { + key: "normalizeResponseConfig", + value: function normalizeResponseConfig() { + // If the response config looks like a status, start to generate a simple response + if (typeof this.responseConfig === 'number') { + this.debug('building response using status', this.responseConfig); + this.responseConfig = { + status: this.responseConfig + }; // If the response config is not an object, or is an object that doesn't use + // any reserved properties, assume it is meant to be the body of the response + } else if (typeof this.responseConfig === 'string' || this.sendAsObject()) { + this.debug('building text response from', this.responseConfig); + this.responseConfig = { + body: this.responseConfig + }; + } + } + }, { + key: "validateStatus", + value: function validateStatus(status) { + if (!status) { + this.debug('No status provided. Defaulting to 200'); + return 200; + } + + if (typeof status === 'number' && parseInt(status, 10) !== status && status >= 200 || status < 600) { + this.debug('Valid status provided', status); + return status; + } + + throw new TypeError("fetch-mock: Invalid status ".concat(status, " passed on response object.\nTo respond with a JSON object that has status as a property assign the object to body\ne.g. {\"body\": {\"status: \"registered\"}}")); + } + }, { + key: "constructFetchOpts", + value: function constructFetchOpts() { + this.options = this.responseConfig.options || {}; + this.options.url = this.responseConfig.redirectUrl || this.url; + this.options.status = this.validateStatus(this.responseConfig.status); + this.options.statusText = this.fetchMock.statusTextMap[String(this.options.status)]; // Set up response headers. The empty object is to cope with + // new Headers(undefined) throwing in Chrome + // https://code.google.com/p/chromium/issues/detail?id=335871 + + this.options.headers = new this.fetchMock.config.Headers(this.responseConfig.headers || {}); + } + }, { + key: "getOption", + value: function getOption(name) { + return this.fetchMock.getOption(name, this.route); + } + }, { + key: "convertToJson", + value: function convertToJson() { + // convert to json if we need to + if (this.getOption('sendAsJson') && this.responseConfig.body != null && //eslint-disable-line + (0, _typeof2["default"])(this.body) === 'object') { + this.debug('Stringifying JSON response body'); + this.body = JSON.stringify(this.body); + + if (!this.options.headers.has('Content-Type')) { + this.options.headers.set('Content-Type', 'application/json'); + } + } + } + }, { + key: "setContentLength", + value: function setContentLength() { + // add a Content-Length header if we need to + if (this.getOption('includeContentLength') && typeof this.body === 'string' && !this.options.headers.has('Content-Length')) { + this.debug('Setting content-length header:', this.body.length.toString()); + this.options.headers.set('Content-Length', this.body.length.toString()); + } + } + }, { + key: "constructResponseBody", + value: function constructResponseBody() { + // start to construct the body + this.body = this.responseConfig.body; + this.convertToJson(); + this.setContentLength(); // On the server we need to manually construct the readable stream for the + // Response object (on the client this done automatically) + + if (this.Stream) { + this.debug('Creating response stream'); + var stream = new this.Stream.Readable(); + + if (this.body != null) { + //eslint-disable-line + stream.push(this.body, 'utf-8'); + } + + stream.push(null); + this.body = stream; + } + + this.body = this.body; + } + }, { + key: "buildObservableResponse", + value: function buildObservableResponse(response) { + var _this2 = this; + + var fetchMock = this.fetchMock; + response._fmResults = {}; // Using a proxy means we can set properties that may not be writable on + // the original Response. It also means we can track the resolution of + // promises returned by res.json(), res.text() etc + + this.debug('Wrapping Response in ES proxy for observability'); + return new Proxy(response, { + get: function get(originalResponse, name) { + if (_this2.responseConfig.redirectUrl) { + if (name === 'url') { + _this2.debug('Retrieving redirect url', _this2.responseConfig.redirectUrl); + + return _this2.responseConfig.redirectUrl; + } + + if (name === 'redirected') { + _this2.debug('Retrieving redirected status', true); + + return true; + } + } + + if (typeof originalResponse[name] === 'function') { + _this2.debug('Wrapping body promises in ES proxies for observability'); + + return new Proxy(originalResponse[name], { + apply: function apply(func, thisArg, args) { + _this2.debug("Calling res.".concat(name)); + + var result = func.apply(response, args); + + if (result.then) { + fetchMock._holdingPromises.push(result["catch"](function () { + return null; + })); + + originalResponse._fmResults[name] = result; + } + + return result; + } + }); + } + + return originalResponse[name]; + } + }); + } + }]); + return ResponseBuilder; + }(); + + var responseBuilder = function (options) { + return new ResponseBuilder(options).exec(); + }; + + function _defineProperty$1(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; + } + + var defineProperty$1 = _defineProperty$1; + + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return arrayLikeToArray(arr); + } + + var arrayWithoutHoles = _arrayWithoutHoles; + + function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); + } + + var iterableToArray = _iterableToArray; + + function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + var nonIterableSpread = _nonIterableSpread; + + function _toConsumableArray(arr) { + return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread(); + } + + var toConsumableArray = _toConsumableArray; + + var _typeof2$1 = interopRequireDefault(_typeof_1); + + var _regenerator = interopRequireDefault(regenerator); + + var _asyncToGenerator2 = interopRequireDefault(asyncToGenerator); + + var _defineProperty2 = interopRequireDefault(defineProperty$1); + + var _slicedToArray2 = interopRequireDefault(slicedToArray); + + var _toConsumableArray2 = interopRequireDefault(toConsumableArray); + + var URL; // https://stackoverflow.com/a/19709846/308237 + // split, URL constructor does not support protocol-relative urls + + var absoluteUrlRX = new RegExp('^[a-z]+://', 'i'); + var protocolRelativeUrlRX = new RegExp('^//', 'i'); + + var headersToArray = function headersToArray(headers) { + // node-fetch 1 Headers + if (typeof headers.raw === 'function') { + return Object.entries(headers.raw()); + } else if (headers[Symbol.iterator]) { + return (0, _toConsumableArray2["default"])(headers); + } else { + return Object.entries(headers); + } + }; + + var zipObject = function zipObject(entries) { + return entries.reduce(function (obj, _ref) { + var _ref2 = (0, _slicedToArray2["default"])(_ref, 2), + key = _ref2[0], + val = _ref2[1]; + + return Object.assign(obj, (0, _defineProperty2["default"])({}, key, val)); + }, {}); + }; + + var normalizeUrl = function normalizeUrl(url) { + if (typeof url === 'function' || url instanceof RegExp || /^(begin|end|glob|express|path)\:/.test(url)) { + return url; + } + + if (absoluteUrlRX.test(url)) { + var u = new URL(url); + return u.href; + } else if (protocolRelativeUrlRX.test(url)) { + var _u = new URL(url, 'http://dummy'); + + return _u.href; + } else { + var _u2 = new URL(url, 'http://dummy'); + + return _u2.pathname + _u2.search; + } + }; + + var extractBody = /*#__PURE__*/function () { + var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(request) { + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + + if (!('body' in request)) { + _context.next = 3; + break; + } + + return _context.abrupt("return", request.body.toString()); + + case 3: + return _context.abrupt("return", request.clone().text()); + + case 6: + _context.prev = 6; + _context.t0 = _context["catch"](0); + + case 8: + case "end": + return _context.stop(); + } + } + }, _callee, null, [[0, 6]]); + })); + + return function extractBody(_x) { + return _ref3.apply(this, arguments); + }; + }(); + + var requestUtils = { + setUrlImplementation: function setUrlImplementation(it) { + URL = it; + }, + normalizeRequest: function normalizeRequest(url, options, Request) { + if (Request.prototype.isPrototypeOf(url)) { + var derivedOptions = { + method: url.method + }; + var body = extractBody(url); + + if (typeof body !== 'undefined') { + derivedOptions.body = body; + } + + var normalizedRequestObject = { + url: normalizeUrl(url.url), + options: Object.assign(derivedOptions, options), + request: url, + signal: options && options.signal || url.signal + }; + var headers = headersToArray(url.headers); + + if (headers.length) { + normalizedRequestObject.options.headers = zipObject(headers); + } + + return normalizedRequestObject; + } else if (typeof url === 'string' || // horrible URL object duck-typing + (0, _typeof2$1["default"])(url) === 'object' && 'href' in url) { + return { + url: normalizeUrl(url), + options: options, + signal: options && options.signal + }; + } else if ((0, _typeof2$1["default"])(url) === 'object') { + throw new TypeError('fetch-mock: Unrecognised Request object. Read the Config and Installation sections of the docs'); + } else { + throw new TypeError('fetch-mock: Invalid arguments passed to fetch'); + } + }, + normalizeUrl: normalizeUrl, + getPath: function getPath(url) { + var u = absoluteUrlRX.test(url) ? new URL(url) : new URL(url, 'http://dummy'); + return u.pathname; + }, + getQuery: function getQuery(url) { + var u = absoluteUrlRX.test(url) ? new URL(url) : new URL(url, 'http://dummy'); + return u.search ? u.search.substr(1) : ''; + }, + headers: { + normalize: function normalize(headers) { + return zipObject(headersToArray(headers)); + }, + toLowerCase: function toLowerCase(headers) { + return Object.keys(headers).reduce(function (obj, k) { + obj[k.toLowerCase()] = headers[k]; + return obj; + }, {}); + }, + equal: function equal(actualHeader, expectedHeader) { + actualHeader = Array.isArray(actualHeader) ? actualHeader : [actualHeader]; + expectedHeader = Array.isArray(expectedHeader) ? expectedHeader : [expectedHeader]; + + if (actualHeader.length !== expectedHeader.length) { + return false; + } + + return actualHeader.every(function (val, i) { + return val === expectedHeader[i]; + }); + } + } + }; + + var _slicedToArray2$1 = interopRequireDefault(slicedToArray); + + var _regenerator$1 = interopRequireDefault(regenerator); + + var _asyncToGenerator2$1 = interopRequireDefault(asyncToGenerator); + + var _classCallCheck2$1 = interopRequireDefault(classCallCheck); + + var _assertThisInitialized2 = interopRequireDefault(assertThisInitialized); + + var _inherits2 = interopRequireDefault(inherits$2); + + var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + + var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + + var _wrapNativeSuper2 = interopRequireDefault(wrapNativeSuper); + + function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } + + function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + + var debug$1 = debug_1.debug, + setDebugPhase$1 = debug_1.setDebugPhase, + getDebug$1 = debug_1.getDebug; + + + + + + var FetchMock$1 = {}; // see https://heycam.github.io/webidl/#aborterror for the standardised interface + // Note that this differs slightly from node-fetch + + var AbortError = /*#__PURE__*/function (_Error) { + (0, _inherits2["default"])(AbortError, _Error); + + var _super = _createSuper(AbortError); + + function AbortError() { + var _this; + + (0, _classCallCheck2$1["default"])(this, AbortError); + _this = _super.apply(this, arguments); + _this.name = 'AbortError'; + _this.message = 'The operation was aborted.'; // Do not include this class in the stacktrace + + if (Error.captureStackTrace) { + Error.captureStackTrace((0, _assertThisInitialized2["default"])(_this), _this.constructor); + } + + return _this; + } + + return AbortError; + }( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error)); // Patch native fetch to avoid "NotSupportedError:ReadableStream uploading is not supported" in Safari. + // See also https://github.com/wheresrhys/fetch-mock/issues/584 + // See also https://stackoverflow.com/a/50952018/1273406 + + + var patchNativeFetchForSafari = function patchNativeFetchForSafari(nativeFetch) { + // Try to patch fetch only on Safari + if (typeof navigator === 'undefined' || !navigator.vendor || navigator.vendor !== 'Apple Computer, Inc.') { + return nativeFetch; + } // It seems the code is working on Safari thus patch native fetch to avoid the error. + + + return /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2$1["default"])( /*#__PURE__*/_regenerator$1["default"].mark(function _callee(request) { + var method, body, cache, credentials, headers, integrity, mode, redirect, referrer, init; + return _regenerator$1["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + method = request.method; + + if (['POST', 'PUT', 'PATCH'].includes(method)) { + _context.next = 3; + break; + } + + return _context.abrupt("return", nativeFetch(request)); + + case 3: + _context.next = 5; + return request.clone().text(); + + case 5: + body = _context.sent; + cache = request.cache, credentials = request.credentials, headers = request.headers, integrity = request.integrity, mode = request.mode, redirect = request.redirect, referrer = request.referrer; + init = { + body: body, + cache: cache, + credentials: credentials, + headers: headers, + integrity: integrity, + mode: mode, + redirect: redirect, + referrer: referrer, + method: method + }; + return _context.abrupt("return", nativeFetch(request.url, init)); + + case 9: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + + return function (_x) { + return _ref.apply(this, arguments); + }; + }(); + }; + + var resolve$3 = /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2$1["default"])( /*#__PURE__*/_regenerator$1["default"].mark(function _callee2(_ref3, url, options, request) { + var response, _ref3$responseIsFetch, responseIsFetch, debug; + + return _regenerator$1["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + response = _ref3.response, _ref3$responseIsFetch = _ref3.responseIsFetch, responseIsFetch = _ref3$responseIsFetch === void 0 ? false : _ref3$responseIsFetch; + debug = getDebug$1('resolve()'); + debug('Recursively resolving function and promise responses'); // We want to allow things like + // - function returning a Promise for a response + // - delaying (using a timeout Promise) a function's execution to generate + // a response + // Because of this we can't safely check for function before Promisey-ness, + // or vice versa. So to keep it DRY, and flexible, we keep trying until we + // have something that looks like neither Promise nor function + + case 3: + + if (!(typeof response === 'function')) { + _context2.next = 18; + break; + } + + debug(' Response is a function'); // in the case of falling back to the network we need to make sure we're using + // the original Request instance, not our normalised url + options + + if (!responseIsFetch) { + _context2.next = 14; + break; + } + + if (!request) { + _context2.next = 10; + break; + } + + debug(' -> Calling fetch with Request instance'); + return _context2.abrupt("return", response(request)); + + case 10: + debug(' -> Calling fetch with url and options'); + return _context2.abrupt("return", response(url, options)); + + case 14: + debug(' -> Calling response function'); + response = response(url, options, request); + + case 16: + _context2.next = 29; + break; + + case 18: + if (!(typeof response.then === 'function')) { + _context2.next = 26; + break; + } + + debug(' Response is a promise'); + debug(' -> Resolving promise'); + _context2.next = 23; + return response; + + case 23: + response = _context2.sent; + _context2.next = 29; + break; + + case 26: + debug(' Response is not a function or a promise'); + debug(' -> Exiting response resolution recursion'); + return _context2.abrupt("return", response); + + case 29: + _context2.next = 3; + break; + + case 31: + case "end": + return _context2.stop(); + } + } + }, _callee2); + })); + + return function resolve(_x2, _x3, _x4, _x5) { + return _ref2.apply(this, arguments); + }; + }(); + + FetchMock$1.needsAsyncBodyExtraction = function (_ref4) { + var request = _ref4.request; + return request && this.routes.some(function (_ref5) { + var usesBody = _ref5.usesBody; + return usesBody; + }); + }; + + FetchMock$1.fetchHandler = function (url, options) { + setDebugPhase$1('handle'); + var debug = getDebug$1('fetchHandler()'); + debug('fetch called with:', url, options); + var normalizedRequest = requestUtils.normalizeRequest(url, options, this.config.Request); + debug('Request normalised'); + debug(' url', normalizedRequest.url); + debug(' options', normalizedRequest.options); + debug(' request', normalizedRequest.request); + debug(' signal', normalizedRequest.signal); + + if (this.needsAsyncBodyExtraction(normalizedRequest)) { + debug('Need to wait for Body to be streamed before calling router: switching to async mode'); + return this._extractBodyThenHandle(normalizedRequest); + } + + return this._fetchHandler(normalizedRequest); + }; + + FetchMock$1._extractBodyThenHandle = /*#__PURE__*/function () { + var _ref6 = (0, _asyncToGenerator2$1["default"])( /*#__PURE__*/_regenerator$1["default"].mark(function _callee3(normalizedRequest) { + return _regenerator$1["default"].wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return normalizedRequest.options.body; + + case 2: + normalizedRequest.options.body = _context3.sent; + return _context3.abrupt("return", this._fetchHandler(normalizedRequest)); + + case 4: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); + + return function (_x6) { + return _ref6.apply(this, arguments); + }; + }(); + + FetchMock$1._fetchHandler = function (_ref7) { + var _this2 = this; + + var url = _ref7.url, + options = _ref7.options, + request = _ref7.request, + signal = _ref7.signal; + + var _this$executeRouter = this.executeRouter(url, options, request), + route = _this$executeRouter.route, + callLog = _this$executeRouter.callLog; + + this.recordCall(callLog); // this is used to power the .flush() method + + var done; + + this._holdingPromises.push(new this.config.Promise(function (res) { + return done = res; + })); // wrapped in this promise to make sure we respect custom Promise + // constructors defined by the user + + + return new this.config.Promise(function (res, rej) { + if (signal) { + debug$1('signal exists - enabling fetch abort'); + + var abort = function abort() { + debug$1('aborting fetch'); // note that DOMException is not available in node.js; + // even node-fetch uses a custom error class: + // https://github.com/bitinn/node-fetch/blob/master/src/abort-error.js + + rej(typeof DOMException !== 'undefined' ? new DOMException('The operation was aborted.', 'AbortError') : new AbortError()); + done(); + }; + + if (signal.aborted) { + debug$1('signal is already aborted - aborting the fetch'); + abort(); + } + + signal.addEventListener('abort', abort); + } + + _this2.generateResponse({ + route: route, + url: url, + options: options, + request: request, + callLog: callLog + }).then(res, rej).then(done, done).then(function () { + setDebugPhase$1(); + }); + }); + }; + + FetchMock$1.fetchHandler.isMock = true; + + FetchMock$1.executeRouter = function (url, options, request) { + var debug = getDebug$1('executeRouter()'); + var callLog = { + url: url, + options: options, + request: request, + isUnmatched: true + }; + debug("Attempting to match request to a route"); + + if (this.getOption('fallbackToNetwork') === 'always') { + debug(' Configured with fallbackToNetwork=always - passing through to fetch'); + return { + route: { + response: this.getNativeFetch(), + responseIsFetch: true + } // BUG - this callLog never used to get sent. Discovered the bug + // but can't fix outside a major release as it will potentially + // cause too much disruption + // + // callLog, + + }; + } + + var route = this.router(url, options, request); + + if (route) { + debug(' Matching route found'); + return { + route: route, + callLog: { + url: url, + options: options, + request: request, + identifier: route.identifier + } + }; + } + + if (this.getOption('warnOnFallback')) { + console.warn("Unmatched ".concat(options && options.method || 'GET', " to ").concat(url)); // eslint-disable-line + } + + if (this.fallbackResponse) { + debug(' No matching route found - using fallbackResponse'); + return { + route: { + response: this.fallbackResponse + }, + callLog: callLog + }; + } + + if (!this.getOption('fallbackToNetwork')) { + throw new Error("fetch-mock: No fallback response defined for ".concat(options && options.method || 'GET', " to ").concat(url)); + } + + debug(' Configured to fallbackToNetwork - passing through to fetch'); + return { + route: { + response: this.getNativeFetch(), + responseIsFetch: true + }, + callLog: callLog + }; + }; + + FetchMock$1.generateResponse = /*#__PURE__*/function () { + var _ref8 = (0, _asyncToGenerator2$1["default"])( /*#__PURE__*/_regenerator$1["default"].mark(function _callee4(_ref9) { + var route, url, options, request, _ref9$callLog, callLog, debug, response, _responseBuilder, _responseBuilder2, realResponse, finalResponse; + + return _regenerator$1["default"].wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + route = _ref9.route, url = _ref9.url, options = _ref9.options, request = _ref9.request, _ref9$callLog = _ref9.callLog, callLog = _ref9$callLog === void 0 ? {} : _ref9$callLog; + debug = getDebug$1('generateResponse()'); + _context4.next = 4; + return resolve$3(route, url, options, request); + + case 4: + response = _context4.sent; + + if (!(response["throws"] && typeof response !== 'function')) { + _context4.next = 8; + break; + } + + debug('response.throws is defined - throwing an error'); + throw response["throws"]; + + case 8: + if (!this.config.Response.prototype.isPrototypeOf(response)) { + _context4.next = 12; + break; + } + + debug('response is already a Response instance - returning it'); + callLog.response = response; + return _context4.abrupt("return", response); + + case 12: + // finally, if we need to convert config into a response, we do it + _responseBuilder = responseBuilder({ + url: url, + responseConfig: response, + fetchMock: this, + route: route + }), _responseBuilder2 = (0, _slicedToArray2$1["default"])(_responseBuilder, 2), realResponse = _responseBuilder2[0], finalResponse = _responseBuilder2[1]; + callLog.response = realResponse; + return _context4.abrupt("return", finalResponse); + + case 15: + case "end": + return _context4.stop(); + } + } + }, _callee4, this); + })); + + return function (_x7) { + return _ref8.apply(this, arguments); + }; + }(); + + FetchMock$1.router = function (url, options, request) { + var route = this.routes.find(function (route, i) { + debug$1("Trying to match route ".concat(i)); + return route.matcher(url, options, request); + }); + + if (route) { + return route; + } + }; + + FetchMock$1.getNativeFetch = function () { + var func = this.realFetch || this.isSandbox && this.config.fetch; + + if (!func) { + throw new Error('fetch-mock: Falling back to network only available on global fetch-mock, or by setting config.fetch on sandboxed fetch-mock'); + } + + return patchNativeFetchForSafari(func); + }; + + FetchMock$1.recordCall = function (obj) { + debug$1('Recording fetch call', obj); + + if (obj) { + this._calls.push(obj); + } + }; + + var fetchHandler = FetchMock$1; + + var globToRegexp = function (glob, opts) { + if (typeof glob !== 'string') { + throw new TypeError('Expected a string'); + } + + var str = String(glob); + + // The regexp we are building, as a string. + var reStr = ""; + + // Whether we are matching so called "extended" globs (like bash) and should + // support single character matching, matching ranges of characters, group + // matching, etc. + var extended = opts ? !!opts.extended : false; + + // When globstar is _false_ (default), '/foo/*' is translated a regexp like + // '^\/foo\/.*$' which will match any string beginning with '/foo/' + // When globstar is _true_, '/foo/*' is translated to regexp like + // '^\/foo\/[^/]*$' which will match any string beginning with '/foo/' BUT + // which does not have a '/' to the right of it. + // E.g. with '/foo/*' these will match: '/foo/bar', '/foo/bar.txt' but + // these will not '/foo/bar/baz', '/foo/bar/baz.txt' + // Lastely, when globstar is _true_, '/foo/**' is equivelant to '/foo/*' when + // globstar is _false_ + var globstar = opts ? !!opts.globstar : false; + + // If we are doing extended matching, this boolean is true when we are inside + // a group (eg {*.html,*.js}), and false otherwise. + var inGroup = false; + + // RegExp flags (eg "i" ) to pass in to RegExp constructor. + var flags = opts && typeof( opts.flags ) === "string" ? opts.flags : ""; + + var c; + for (var i = 0, len = str.length; i < len; i++) { + c = str[i]; + + switch (c) { + case "/": + case "$": + case "^": + case "+": + case ".": + case "(": + case ")": + case "=": + case "!": + case "|": + reStr += "\\" + c; + break; + + case "?": + if (extended) { + reStr += "."; + break; + } + + case "[": + case "]": + if (extended) { + reStr += c; + break; + } + + case "{": + if (extended) { + inGroup = true; + reStr += "("; + break; + } + + case "}": + if (extended) { + inGroup = false; + reStr += ")"; + break; + } + + case ",": + if (inGroup) { + reStr += "|"; + break; + } + reStr += "\\" + c; + break; + + case "*": + // Move over all consecutive "*"'s. + // Also store the previous and next characters + var prevChar = str[i - 1]; + var starCount = 1; + while(str[i + 1] === "*") { + starCount++; + i++; + } + var nextChar = str[i + 1]; + + if (!globstar) { + // globstar is disabled, so treat any number of "*" as one + reStr += ".*"; + } else { + // globstar is enabled, so determine if this is a globstar segment + var isGlobstar = starCount > 1 // multiple "*"'s + && (prevChar === "/" || prevChar === undefined) // from the start of the segment + && (nextChar === "/" || nextChar === undefined); // to the end of the segment + + if (isGlobstar) { + // it's a globstar, so match zero or more path segments + reStr += "((?:[^/]*(?:\/|$))*)"; + i++; // move over the "/" + } else { + // it's not a globstar, so only match one path segment + reStr += "([^/]*)"; + } + } + break; + + default: + reStr += c; + } + } + + // When regexp 'g' flag is specified don't + // constrain the regular expression with ^ & $ + if (!flags || !~flags.indexOf('g')) { + reStr = "^" + reStr + "$"; + } + + return new RegExp(reStr, flags); + }; + + /** + * Expose `pathToRegexp`. + */ + var pathToRegexp_1 = pathToRegexp; + var parse_1$1 = parse$6; + var compile_1 = compile; + var tokensToFunction_1 = tokensToFunction; + var tokensToRegExp_1 = tokensToRegExp; + + /** + * Default configs. + */ + var DEFAULT_DELIMITER = '/'; + var DEFAULT_DELIMITERS = './'; + + /** + * The main path matching regexp utility. + * + * @type {RegExp} + */ + var PATH_REGEXP = new RegExp([ + // Match escaped characters that would otherwise appear in future matches. + // This allows the user to escape special characters that won't transform. + '(\\\\.)', + // Match Express-style parameters and un-named parameters with a prefix + // and optional suffixes. Matches appear as: + // + // ":test(\\d+)?" => ["test", "\d+", undefined, "?"] + // "(\\d+)" => [undefined, undefined, "\d+", undefined] + '(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?' + ].join('|'), 'g'); + + /** + * Parse a string for the raw tokens. + * + * @param {string} str + * @param {Object=} options + * @return {!Array} + */ + function parse$6 (str, options) { + var tokens = []; + var key = 0; + var index = 0; + var path = ''; + var defaultDelimiter = (options && options.delimiter) || DEFAULT_DELIMITER; + var delimiters = (options && options.delimiters) || DEFAULT_DELIMITERS; + var pathEscaped = false; + var res; + + while ((res = PATH_REGEXP.exec(str)) !== null) { + var m = res[0]; + var escaped = res[1]; + var offset = res.index; + path += str.slice(index, offset); + index = offset + m.length; + + // Ignore already escaped sequences. + if (escaped) { + path += escaped[1]; + pathEscaped = true; + continue + } + + var prev = ''; + var next = str[index]; + var name = res[2]; + var capture = res[3]; + var group = res[4]; + var modifier = res[5]; + + if (!pathEscaped && path.length) { + var k = path.length - 1; + + if (delimiters.indexOf(path[k]) > -1) { + prev = path[k]; + path = path.slice(0, k); + } + } + + // Push the current path onto the tokens. + if (path) { + tokens.push(path); + path = ''; + pathEscaped = false; + } + + var partial = prev !== '' && next !== undefined && next !== prev; + var repeat = modifier === '+' || modifier === '*'; + var optional = modifier === '?' || modifier === '*'; + var delimiter = prev || defaultDelimiter; + var pattern = capture || group; + + tokens.push({ + name: name || key++, + prefix: prev, + delimiter: delimiter, + optional: optional, + repeat: repeat, + partial: partial, + pattern: pattern ? escapeGroup(pattern) : '[^' + escapeString(delimiter) + ']+?' + }); + } + + // Push any remaining characters. + if (path || index < str.length) { + tokens.push(path + str.substr(index)); + } + + return tokens + } + + /** + * Compile a string to a template function for the path. + * + * @param {string} str + * @param {Object=} options + * @return {!function(Object=, Object=)} + */ + function compile (str, options) { + return tokensToFunction(parse$6(str, options)) + } + + /** + * Expose a method for transforming tokens into the path function. + */ + function tokensToFunction (tokens) { + // Compile all the tokens into regexps. + var matches = new Array(tokens.length); + + // Compile all the patterns before compilation. + for (var i = 0; i < tokens.length; i++) { + if (typeof tokens[i] === 'object') { + matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$'); + } + } + + return function (data, options) { + var path = ''; + var encode = (options && options.encode) || encodeURIComponent; + + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + + if (typeof token === 'string') { + path += token; + continue + } + + var value = data ? data[token.name] : undefined; + var segment; + + if (Array.isArray(value)) { + if (!token.repeat) { + throw new TypeError('Expected "' + token.name + '" to not repeat, but got array') + } + + if (value.length === 0) { + if (token.optional) continue + + throw new TypeError('Expected "' + token.name + '" to not be empty') + } + + for (var j = 0; j < value.length; j++) { + segment = encode(value[j], token); + + if (!matches[i].test(segment)) { + throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '"') + } + + path += (j === 0 ? token.prefix : token.delimiter) + segment; + } + + continue + } + + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + segment = encode(String(value), token); + + if (!matches[i].test(segment)) { + throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but got "' + segment + '"') + } + + path += token.prefix + segment; + continue + } + + if (token.optional) { + // Prepend partial segment prefixes. + if (token.partial) path += token.prefix; + + continue + } + + throw new TypeError('Expected "' + token.name + '" to be ' + (token.repeat ? 'an array' : 'a string')) + } + + return path + } + } + + /** + * Escape a regular expression string. + * + * @param {string} str + * @return {string} + */ + function escapeString (str) { + return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1') + } + + /** + * Escape the capturing group by escaping special characters and meaning. + * + * @param {string} group + * @return {string} + */ + function escapeGroup (group) { + return group.replace(/([=!:$/()])/g, '\\$1') + } + + /** + * Get the flags for a regexp from the options. + * + * @param {Object} options + * @return {string} + */ + function flags (options) { + return options && options.sensitive ? '' : 'i' + } + + /** + * Pull out keys from a regexp. + * + * @param {!RegExp} path + * @param {Array=} keys + * @return {!RegExp} + */ + function regexpToRegexp (path, keys) { + if (!keys) return path + + // Use a negative lookahead to match only capturing groups. + var groups = path.source.match(/\((?!\?)/g); + + if (groups) { + for (var i = 0; i < groups.length; i++) { + keys.push({ + name: i, + prefix: null, + delimiter: null, + optional: false, + repeat: false, + partial: false, + pattern: null + }); + } + } + + return path + } + + /** + * Transform an array into a regexp. + * + * @param {!Array} path + * @param {Array=} keys + * @param {Object=} options + * @return {!RegExp} + */ + function arrayToRegexp (path, keys, options) { + var parts = []; + + for (var i = 0; i < path.length; i++) { + parts.push(pathToRegexp(path[i], keys, options).source); + } + + return new RegExp('(?:' + parts.join('|') + ')', flags(options)) + } + + /** + * Create a path regexp from string input. + * + * @param {string} path + * @param {Array=} keys + * @param {Object=} options + * @return {!RegExp} + */ + function stringToRegexp (path, keys, options) { + return tokensToRegExp(parse$6(path, options), keys, options) + } + + /** + * Expose a function for taking tokens and returning a RegExp. + * + * @param {!Array} tokens + * @param {Array=} keys + * @param {Object=} options + * @return {!RegExp} + */ + function tokensToRegExp (tokens, keys, options) { + options = options || {}; + + var strict = options.strict; + var start = options.start !== false; + var end = options.end !== false; + var delimiter = escapeString(options.delimiter || DEFAULT_DELIMITER); + var delimiters = options.delimiters || DEFAULT_DELIMITERS; + var endsWith = [].concat(options.endsWith || []).map(escapeString).concat('$').join('|'); + var route = start ? '^' : ''; + var isEndDelimited = tokens.length === 0; + + // Iterate over the tokens and create our regexp string. + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + + if (typeof token === 'string') { + route += escapeString(token); + isEndDelimited = i === tokens.length - 1 && delimiters.indexOf(token[token.length - 1]) > -1; + } else { + var capture = token.repeat + ? '(?:' + token.pattern + ')(?:' + escapeString(token.delimiter) + '(?:' + token.pattern + '))*' + : token.pattern; + + if (keys) keys.push(token); + + if (token.optional) { + if (token.partial) { + route += escapeString(token.prefix) + '(' + capture + ')?'; + } else { + route += '(?:' + escapeString(token.prefix) + '(' + capture + '))?'; + } + } else { + route += escapeString(token.prefix) + '(' + capture + ')'; + } + } + } + + if (end) { + if (!strict) route += '(?:' + delimiter + ')?'; + + route += endsWith === '$' ? '$' : '(?=' + endsWith + ')'; + } else { + if (!strict) route += '(?:' + delimiter + '(?=' + endsWith + '))?'; + if (!isEndDelimited) route += '(?=' + delimiter + '|' + endsWith + ')'; + } + + return new RegExp(route, flags(options)) + } + + /** + * Normalize the given path string, returning a regular expression. + * + * An empty array can be passed in for the keys, which will hold the + * placeholder key descriptions. For example, using `/user/:id`, `keys` will + * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`. + * + * @param {(string|RegExp|Array)} path + * @param {Array=} keys + * @param {Object=} options + * @return {!RegExp} + */ + function pathToRegexp (path, keys, options) { + if (path instanceof RegExp) { + return regexpToRegexp(path, keys) + } + + if (Array.isArray(path)) { + return arrayToRegexp(/** @type {!Array} */ (path), keys, options) + } + + return stringToRegexp(/** @type {string} */ (path), keys, options) + } + pathToRegexp_1.parse = parse_1$1; + pathToRegexp_1.compile = compile_1; + pathToRegexp_1.tokensToFunction = tokensToFunction_1; + pathToRegexp_1.tokensToRegExp = tokensToRegExp_1; + + var isSubset_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, '__esModule', { + value: true + }); + /** + * Check if an object is contained within another object. + * + * Returns `true` if: + * - all enumerable keys of *subset* are also enumerable in *superset*, and + * - every value assigned to an enumerable key of *subset* strictly equals + * the value assigned to the same key of *superset* – or is a subset of it. + * + * @param {Object} superset + * @param {Object} subset + * + * @returns {Boolean} + * + * @module is-subset + * @function default + * @alias isSubset + */ + var isSubset = (function (_isSubset) { + function isSubset(_x, _x2) { + return _isSubset.apply(this, arguments); + } + + isSubset.toString = function () { + return _isSubset.toString(); + }; + + return isSubset; + })(function (superset, subset) { + if (typeof superset !== 'object' || superset === null || (typeof subset !== 'object' || subset === null)) return false; + + return Object.keys(subset).every(function (key) { + if (!superset.propertyIsEnumerable(key)) return false; + + var subsetItem = subset[key]; + var supersetItem = superset[key]; + if (typeof subsetItem === 'object' && subsetItem !== null ? !isSubset(supersetItem, subsetItem) : supersetItem !== subsetItem) return false; + + return true; + }); + }); + + exports['default'] = isSubset; + module.exports = exports['default']; + }); + + unwrapExports(isSubset_1); + + var lodash_isequal = createCommonjsModule(function (module, exports) { + /** + * Lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright JS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + + /** Used as references for various `Number` constants. */ + var MAX_SAFE_INTEGER = 9007199254740991; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + nullTag = '[object Null]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + undefinedTag = '[object Undefined]', + weakMapTag = '[object WeakMap]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); + + /** Detect free variable `exports`. */ + var freeExports = exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process; + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); + + /* Node.js helper references. */ + var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key); + } + + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } + + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + + /** Used to detect overreaching core-js shims. */ + var coreJsData = root['__core-js_shared__']; + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var nativeObjectToString = objectProto.toString; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** Built-in value references. */ + var Buffer = moduleExports ? root.Buffer : undefined, + Symbol = root.Symbol, + Uint8Array = root.Uint8Array, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + symToStringTag = Symbol ? Symbol.toStringTag : undefined; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeKeys = overArg(Object.keys, Object); + + /* Built-in method references that are verified to be native. */ + var DataView = getNative(root, 'DataView'), + Map = getNative(root, 'Map'), + Promise = getNative(root, 'Promise'), + Set = getNative(root, 'Set'), + WeakMap = getNative(root, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; + + /** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + + /** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; + } + + /** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); + } + + /** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + + /** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + + /** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; + } + + /** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + + /** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; + } + + /** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + + /** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + + /** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + /** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } + } + + /** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; + } + + /** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ + function setCacheHas(value) { + return this.__data__.has(value); + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + /** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + + /** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; + } + + /** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; + } + + /** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function stackGet(key) { + return this.__data__.get(key); + } + + /** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function stackHas(key) { + return this.__data__.has(key); + } + + /** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; + } + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + + /** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } + + /** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); + } + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; + } + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other); + + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); + } + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; + } + + /** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); + } + + /** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; + } + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } + + /** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; + } + + /** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); + }; + + /** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; + } + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); + } + + /** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; + } + + /** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + function objectToString(value) { + return nativeObjectToString.call(value); + } + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse; + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other); + } + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == 'object'; + } + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + + /** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ + function stubArray() { + return []; + } + + /** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ + function stubFalse() { + return false; + } + + module.exports = isEqual; + }); + + var querystring$2 = getCjsExportFromNamespace(qs$1); + + var _defineProperty2$1 = interopRequireDefault(defineProperty$1); + + var debug$2 = debug_1.debug; + + + + + + + + + + var headerUtils = requestUtils.headers, + getPath = requestUtils.getPath, + getQuery = requestUtils.getQuery, + normalizeUrl$1 = requestUtils.normalizeUrl; + + + + var debuggableUrlFunc = function debuggableUrlFunc(func) { + return function (url) { + debug$2('Actual url:', url); + return func(url); + }; + }; + + var stringMatchers = { + begin: function begin(targetString) { + return debuggableUrlFunc(function (url) { + return url.indexOf(targetString) === 0; + }); + }, + end: function end(targetString) { + return debuggableUrlFunc(function (url) { + return url.substr(-targetString.length) === targetString; + }); + }, + glob: function glob(targetString) { + var urlRX = globToRegexp(targetString); + + return debuggableUrlFunc(function (url) { + return urlRX.test(url); + }); + }, + express: function express(targetString) { + var urlRX = pathToRegexp_1(targetString); + return debuggableUrlFunc(function (url) { + return urlRX.test(getPath(url)); + }); + }, + path: function path(targetString) { + return debuggableUrlFunc(function (url) { + return getPath(url) === targetString; + }); + } + }; + + var getHeaderMatcher = function getHeaderMatcher(_ref) { + var expectedHeaders = _ref.headers; + debug$2('Generating header matcher'); + + if (!expectedHeaders) { + debug$2(' No header expectations defined - skipping'); + return; + } + + var expectation = headerUtils.toLowerCase(expectedHeaders); + debug$2(' Expected headers:', expectation); + return function (url, _ref2) { + var _ref2$headers = _ref2.headers, + headers = _ref2$headers === void 0 ? {} : _ref2$headers; + debug$2('Attempting to match headers'); + var lowerCaseHeaders = headerUtils.toLowerCase(headerUtils.normalize(headers)); + debug$2(' Expected headers:', expectation); + debug$2(' Actual headers:', lowerCaseHeaders); + return Object.keys(expectation).every(function (headerName) { + return headerUtils.equal(lowerCaseHeaders[headerName], expectation[headerName]); + }); + }; + }; + + var getMethodMatcher = function getMethodMatcher(_ref3) { + var expectedMethod = _ref3.method; + debug$2('Generating method matcher'); + + if (!expectedMethod) { + debug$2(' No method expectations defined - skipping'); + return; + } + + debug$2(' Expected method:', expectedMethod); + return function (url, _ref4) { + var method = _ref4.method; + debug$2('Attempting to match method'); + var actualMethod = method ? method.toLowerCase() : 'get'; + debug$2(' Expected method:', expectedMethod); + debug$2(' Actual method:', actualMethod); + return expectedMethod === actualMethod; + }; + }; + + var getQueryStringMatcher = function getQueryStringMatcher(_ref5) { + var passedQuery = _ref5.query; + debug$2('Generating query parameters matcher'); + + if (!passedQuery) { + debug$2(' No query parameters expectations defined - skipping'); + return; + } + + var expectedQuery = querystring$2.parse(querystring$2.stringify(passedQuery)); + debug$2(' Expected query parameters:', passedQuery); + var keys = Object.keys(expectedQuery); + return function (url) { + debug$2('Attempting to match query parameters'); + var query = querystring$2.parse(getQuery(url)); + debug$2(' Expected query parameters:', expectedQuery); + debug$2(' Actual query parameters:', query); + return keys.every(function (key) { + if (Array.isArray(query[key])) { + if (!Array.isArray(expectedQuery[key])) { + return false; + } else { + return lodash_isequal(query[key].sort(), expectedQuery[key].sort()); + } + } + + return query[key] === expectedQuery[key]; + }); + }; + }; + + var getParamsMatcher = function getParamsMatcher(_ref6) { + var expectedParams = _ref6.params, + matcherUrl = _ref6.url; + debug$2('Generating path parameters matcher'); + + if (!expectedParams) { + debug$2(' No path parameters expectations defined - skipping'); + return; + } + + if (!/express:/.test(matcherUrl)) { + throw new Error('fetch-mock: matching on params is only possible when using an express: matcher'); + } + + debug$2(' Expected path parameters:', expectedParams); + var expectedKeys = Object.keys(expectedParams); + var keys = []; + var re = pathToRegexp_1(matcherUrl.replace(/^express:/, ''), keys); + return function (url) { + debug$2('Attempting to match path parameters'); + var vals = re.exec(getPath(url)) || []; + vals.shift(); + var params = keys.reduce(function (map, _ref7, i) { + var name = _ref7.name; + return vals[i] ? Object.assign(map, (0, _defineProperty2$1["default"])({}, name, vals[i])) : map; + }, {}); + debug$2(' Expected path parameters:', expectedParams); + debug$2(' Actual path parameters:', params); + return expectedKeys.every(function (key) { + return params[key] === expectedParams[key]; + }); + }; + }; + + var getBodyMatcher = function getBodyMatcher(route, fetchMock) { + var matchPartialBody = fetchMock.getOption('matchPartialBody', route); + var expectedBody = route.body; + debug$2('Generating body matcher'); + return function (url, _ref8) { + var body = _ref8.body, + _ref8$method = _ref8.method, + method = _ref8$method === void 0 ? 'get' : _ref8$method; + debug$2('Attempting to match body'); + + if (method.toLowerCase() === 'get') { + debug$2(' GET request - skip matching body'); // GET requests don’t send a body so the body matcher should be ignored for them + + return true; + } + + var sentBody = body; + + try { + debug$2(' Parsing request body as JSON'); + sentBody = JSON.parse(body); + } catch (err) { + debug$2(' Failed to parse request body as JSON', err); + } + + debug$2('Expected body:', expectedBody); + debug$2('Actual body:', sentBody); + + if (matchPartialBody) { + debug$2('matchPartialBody is true - checking for partial match only'); + } + + return sentBody && (matchPartialBody ? isSubset_1(sentBody, expectedBody) : lodash_isequal(sentBody, expectedBody)); + }; + }; + + var getFullUrlMatcher = function getFullUrlMatcher(route, matcherUrl, query) { + // if none of the special syntaxes apply, it's just a simple string match + // but we have to be careful to normalize the url we check and the name + // of the route to allow for e.g. http://it.at.there being indistinguishable + // from http://it.at.there/ once we start generating Request/Url objects + debug$2(' Matching using full url', matcherUrl); + var expectedUrl = normalizeUrl$1(matcherUrl); + debug$2(' Normalised url to:', matcherUrl); + + if (route.identifier === matcherUrl) { + debug$2(' Updating route identifier to match normalized url:', matcherUrl); + route.identifier = expectedUrl; + } + + return function (matcherUrl) { + debug$2('Expected url:', expectedUrl); + debug$2('Actual url:', matcherUrl); + + if (query && expectedUrl.indexOf('?')) { + debug$2('Ignoring query string when matching url'); + return matcherUrl.indexOf(expectedUrl) === 0; + } + + return normalizeUrl$1(matcherUrl) === expectedUrl; + }; + }; + + var getFunctionMatcher = function getFunctionMatcher(_ref9) { + var functionMatcher = _ref9.functionMatcher; + debug$2('Detected user defined function matcher', functionMatcher); + return function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + debug$2('Calling function matcher with arguments', args); + return functionMatcher.apply(void 0, args); + }; + }; + + var getUrlMatcher = function getUrlMatcher(route) { + debug$2('Generating url matcher'); + var matcherUrl = route.url, + query = route.query; + + if (matcherUrl === '*') { + debug$2(' Using universal * rule to match any url'); + return function () { + return true; + }; + } + + if (matcherUrl instanceof RegExp) { + debug$2(' Using regular expression to match url:', matcherUrl); + return function (url) { + return matcherUrl.test(url); + }; + } + + if (matcherUrl.href) { + debug$2(" Using URL object to match url", matcherUrl); + return getFullUrlMatcher(route, matcherUrl.href, query); + } + + for (var shorthand in stringMatchers) { + if (matcherUrl.indexOf(shorthand + ':') === 0) { + debug$2(" Using ".concat(shorthand, ": pattern to match url"), matcherUrl); + var urlFragment = matcherUrl.replace(new RegExp("^".concat(shorthand, ":")), ''); + return stringMatchers[shorthand](urlFragment); + } + } + + return getFullUrlMatcher(route, matcherUrl, query); + }; + + var matchers = [{ + name: 'query', + matcher: getQueryStringMatcher + }, { + name: 'method', + matcher: getMethodMatcher + }, { + name: 'headers', + matcher: getHeaderMatcher + }, { + name: 'params', + matcher: getParamsMatcher + }, { + name: 'body', + matcher: getBodyMatcher, + usesBody: true + }, { + name: 'functionMatcher', + matcher: getFunctionMatcher + }, { + name: 'url', + matcher: getUrlMatcher + }]; + + var _slicedToArray2$2 = interopRequireDefault(slicedToArray); + + var _classCallCheck2$2 = interopRequireDefault(classCallCheck); + + var _createClass2$1 = interopRequireDefault(createClass); + + var _typeof2$2 = interopRequireDefault(_typeof_1); + + + + var debug$3 = debug_1.debug, + setDebugNamespace = debug_1.setDebugNamespace, + getDebug$2 = debug_1.getDebug; + + var isUrlMatcher = function isUrlMatcher(matcher) { + return matcher instanceof RegExp || typeof matcher === 'string' || (0, _typeof2$2["default"])(matcher) === 'object' && 'href' in matcher; + }; + + var isFunctionMatcher = function isFunctionMatcher(matcher) { + return typeof matcher === 'function'; + }; + + var Route = /*#__PURE__*/function () { + function Route(args, fetchMock) { + (0, _classCallCheck2$2["default"])(this, Route); + this.fetchMock = fetchMock; + var debug = getDebug$2('compileRoute()'); + debug('Compiling route'); + this.init(args); + this.sanitize(); + this.validate(); + this.generateMatcher(); + this.limit(); + this.delayResponse(); + } + + (0, _createClass2$1["default"])(Route, [{ + key: "validate", + value: function validate() { + var _this = this; + + if (!('response' in this)) { + throw new Error('fetch-mock: Each route must define a response'); + } + + if (!Route.registeredMatchers.some(function (_ref) { + var name = _ref.name; + return name in _this; + })) { + throw new Error("fetch-mock: Each route must specify some criteria for matching calls to fetch. To match all calls use '*'"); + } + } + }, { + key: "init", + value: function init(args) { + var _args = (0, _slicedToArray2$2["default"])(args, 3), + matcher = _args[0], + response = _args[1], + _args$ = _args[2], + options = _args$ === void 0 ? {} : _args$; + + var routeConfig = {}; + + if (isUrlMatcher(matcher) || isFunctionMatcher(matcher)) { + routeConfig.matcher = matcher; + } else { + Object.assign(routeConfig, matcher); + } + + if (typeof response !== 'undefined') { + routeConfig.response = response; + } + + Object.assign(routeConfig, options); + Object.assign(this, routeConfig); + } + }, { + key: "sanitize", + value: function sanitize() { + var debug = getDebug$2('sanitize()'); + debug('Sanitizing route properties'); + + if (this.method) { + debug("Converting method ".concat(this.method, " to lower case")); + this.method = this.method.toLowerCase(); + } + + if (isUrlMatcher(this.matcher)) { + debug('Mock uses a url matcher', this.matcher); + this.url = this.matcher; + delete this.matcher; + } + + this.functionMatcher = this.matcher || this.functionMatcher; + debug('Setting route.identifier...'); + debug(" route.name is ".concat(this.name)); + debug(" route.url is ".concat(this.url)); + debug(" route.functionMatcher is ".concat(this.functionMatcher)); + this.identifier = this.name || this.url || this.functionMatcher; + debug(" -> route.identifier set to ".concat(this.identifier)); + } + }, { + key: "generateMatcher", + value: function generateMatcher() { + var _this2 = this; + + setDebugNamespace('generateMatcher()'); + debug$3('Compiling matcher for route'); + var activeMatchers = Route.registeredMatchers.map(function (_ref2) { + var name = _ref2.name, + matcher = _ref2.matcher, + usesBody = _ref2.usesBody; + return _this2[name] && { + matcher: matcher(_this2, _this2.fetchMock), + usesBody: usesBody + }; + }).filter(function (matcher) { + return Boolean(matcher); + }); + this.usesBody = activeMatchers.some(function (_ref3) { + var usesBody = _ref3.usesBody; + return usesBody; + }); + debug$3('Compiled matcher for route'); + setDebugNamespace(); + + this.matcher = function (url) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var request = arguments.length > 2 ? arguments[2] : undefined; + return activeMatchers.every(function (_ref4) { + var matcher = _ref4.matcher; + return matcher(url, options, request); + }); + }; + } + }, { + key: "limit", + value: function limit() { + var _this3 = this; + + var debug = getDebug$2('limit()'); + debug('Limiting number of requests to handle by route'); + + if (!this.repeat) { + debug(' No `repeat` value set on route. Will match any number of requests'); + return; + } + + debug(" Route set to repeat ".concat(this.repeat, " times")); + var matcher = this.matcher; + var timesLeft = this.repeat; + + this.matcher = function (url, options) { + var match = timesLeft && matcher(url, options); + + if (match) { + timesLeft--; + return true; + } + }; + + this.reset = function () { + return timesLeft = _this3.repeat; + }; + } + }, { + key: "delayResponse", + value: function delayResponse() { + var _this4 = this; + + var debug = getDebug$2('delayResponse()'); + debug("Applying response delay settings"); + + if (this.delay) { + debug(" Wrapping response in delay of ".concat(this.delay, " miliseconds")); + var response = this.response; + + this.response = function () { + debug("Delaying response by ".concat(_this4.delay, " miliseconds")); + return new Promise(function (res) { + return setTimeout(function () { + return res(response); + }, _this4.delay); + }); + }; + } else { + debug(" No delay set on route. Will respond 'immediately' (but asynchronously)"); + } + } + }], [{ + key: "addMatcher", + value: function addMatcher(matcher) { + Route.registeredMatchers.push(matcher); + } + }]); + return Route; + }(); + + Route.registeredMatchers = []; + matchers.forEach(Route.addMatcher); + var Route_1 = Route; + + var _regenerator$2 = interopRequireDefault(regenerator); + + var _asyncToGenerator2$2 = interopRequireDefault(asyncToGenerator); + + var _slicedToArray2$3 = interopRequireDefault(slicedToArray); + + var _toConsumableArray2$1 = interopRequireDefault(toConsumableArray); + + var setDebugPhase$2 = debug_1.setDebugPhase, + setDebugNamespace$1 = debug_1.setDebugNamespace, + debug$4 = debug_1.debug; + + var normalizeUrl$2 = requestUtils.normalizeUrl; + + + + var FetchMock$2 = {}; + + var isName = function isName(nameOrMatcher) { + return typeof nameOrMatcher === 'string' && /^[\da-zA-Z\-]+$/.test(nameOrMatcher); + }; + + var filterCallsWithMatcher = function filterCallsWithMatcher(matcher) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var calls = arguments.length > 2 ? arguments[2] : undefined; + + var _Route = new Route_1([Object.assign({ + matcher: matcher, + response: 'ok' + }, options)], this); + + matcher = _Route.matcher; + return calls.filter(function (_ref) { + var url = _ref.url, + options = _ref.options; + return matcher(normalizeUrl$2(url), options); + }); + }; + + var formatDebug = function formatDebug(func) { + return function () { + setDebugPhase$2('inspect'); + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var result = func.call.apply(func, [this].concat(args)); + setDebugPhase$2(); + return result; + }; + }; + + var callObjToArray = function callObjToArray(obj) { + if (!obj) { + return undefined; + } + + var url = obj.url, + options = obj.options, + request = obj.request, + identifier = obj.identifier, + isUnmatched = obj.isUnmatched, + response = obj.response; + var arr = [url, options]; + arr.request = request; + arr.identifier = identifier; + arr.isUnmatched = isUnmatched; + arr.response = response; + return arr; + }; + + FetchMock$2.filterCalls = function (nameOrMatcher, options) { + debug$4('Filtering fetch calls'); + var calls = this._calls; + var matcher = '*'; + + if ([true, 'matched'].includes(nameOrMatcher)) { + debug$4("Filter provided is ".concat(nameOrMatcher, ". Returning matched calls only")); + calls = calls.filter(function (_ref2) { + var isUnmatched = _ref2.isUnmatched; + return !isUnmatched; + }); + } else if ([false, 'unmatched'].includes(nameOrMatcher)) { + debug$4("Filter provided is ".concat(nameOrMatcher, ". Returning unmatched calls only")); + calls = calls.filter(function (_ref3) { + var isUnmatched = _ref3.isUnmatched; + return isUnmatched; + }); + } else if (typeof nameOrMatcher === 'undefined') { + debug$4("Filter provided is undefined. Returning all calls"); + calls = calls; + } else if (isName(nameOrMatcher)) { + debug$4("Filter provided, looks like the name of a named route. Returning only calls handled by that route"); + calls = calls.filter(function (_ref4) { + var identifier = _ref4.identifier; + return identifier === nameOrMatcher; + }); + } else { + matcher = nameOrMatcher === '*' ? '*' : normalizeUrl$2(nameOrMatcher); + + if (this.routes.some(function (_ref5) { + var identifier = _ref5.identifier; + return identifier === matcher; + })) { + debug$4("Filter provided, ".concat(nameOrMatcher, ", identifies a route. Returning only calls handled by that route")); + calls = calls.filter(function (call) { + return call.identifier === matcher; + }); + } + } + + if ((options || matcher !== '*') && calls.length) { + if (typeof options === 'string') { + options = { + method: options + }; + } + + debug$4('Compiling filter and options to route in order to filter all calls', nameOrMatcher); + calls = filterCallsWithMatcher.call(this, matcher, options, calls); + } + + debug$4("Retrieved ".concat(calls.length, " calls")); + return calls.map(callObjToArray); + }; + + FetchMock$2.calls = formatDebug(function (nameOrMatcher, options) { + debug$4('retrieving matching calls'); + return this.filterCalls(nameOrMatcher, options); + }); + FetchMock$2.lastCall = formatDebug(function (nameOrMatcher, options) { + debug$4('retrieving last matching call'); + return (0, _toConsumableArray2$1["default"])(this.filterCalls(nameOrMatcher, options)).pop(); + }); + FetchMock$2.lastUrl = formatDebug(function (nameOrMatcher, options) { + debug$4('retrieving url of last matching call'); + return (this.lastCall(nameOrMatcher, options) || [])[0]; + }); + FetchMock$2.lastOptions = formatDebug(function (nameOrMatcher, options) { + debug$4('retrieving options of last matching call'); + return (this.lastCall(nameOrMatcher, options) || [])[1]; + }); + FetchMock$2.lastResponse = formatDebug(function (nameOrMatcher, options) { + debug$4('retrieving respose of last matching call'); + console.warn("When doing all the following:\n- using node-fetch\n- responding with a real network response (using spy() or fallbackToNetwork)\n- using `fetchMock.LastResponse()`\n- awaiting the body content\n... the response will hang unless your source code also awaits the response body.\nThis is an unavoidable consequence of the nodejs implementation of streams.\n"); + var response = (this.lastCall(nameOrMatcher, options) || []).response; + + try { + var clonedResponse = response.clone(); + return clonedResponse; + } catch (err) { + Object.entries(response._fmResults).forEach(function (_ref6) { + var _ref7 = (0, _slicedToArray2$3["default"])(_ref6, 2), + name = _ref7[0], + result = _ref7[1]; + + response[name] = function () { + return result; + }; + }); + return response; + } + }); + FetchMock$2.called = formatDebug(function (nameOrMatcher, options) { + debug$4('checking if matching call was made'); + return Boolean(this.filterCalls(nameOrMatcher, options).length); + }); + FetchMock$2.flush = formatDebug( /*#__PURE__*/function () { + var _ref8 = (0, _asyncToGenerator2$2["default"])( /*#__PURE__*/_regenerator$2["default"].mark(function _callee(waitForResponseMethods) { + var queuedPromises; + return _regenerator$2["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + setDebugNamespace$1('flush'); + debug$4("flushing all fetch calls. ".concat(waitForResponseMethods ? '' : 'Not ', "waiting for response bodies to complete download")); + queuedPromises = this._holdingPromises; + this._holdingPromises = []; + debug$4("".concat(queuedPromises.length, " fetch calls to be awaited")); + _context.next = 7; + return Promise.all(queuedPromises); + + case 7: + debug$4("All fetch calls have completed"); + + if (!(waitForResponseMethods && this._holdingPromises.length)) { + _context.next = 13; + break; + } + + debug$4("Awaiting all fetch bodies to download"); + _context.next = 12; + return this.flush(waitForResponseMethods); + + case 12: + debug$4("All fetch bodies have completed downloading"); + + case 13: + setDebugNamespace$1(); + + case 14: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + return function (_x) { + return _ref8.apply(this, arguments); + }; + }()); + FetchMock$2.done = formatDebug(function (nameOrMatcher) { + var _this = this; + + setDebugPhase$2('inspect'); + setDebugNamespace$1('done'); + debug$4('Checking to see if expected calls have been made'); + var routesToCheck; + + if (nameOrMatcher && typeof nameOrMatcher !== 'boolean') { + debug$4('Checking to see if expected calls have been made for single route:', nameOrMatcher); + routesToCheck = [{ + identifier: nameOrMatcher + }]; + } else { + debug$4('Checking to see if expected calls have been made for all routes'); + routesToCheck = this.routes; + } // Can't use array.every because would exit after first failure, which would + // break the logging + + + var result = routesToCheck.map(function (_ref9) { + var identifier = _ref9.identifier; + + if (!_this.called(identifier)) { + debug$4('No calls made for route:', identifier); + console.warn("Warning: ".concat(identifier, " not called")); // eslint-disable-line + + return false; + } + + var expectedTimes = (_this.routes.find(function (r) { + return r.identifier === identifier; + }) || {}).repeat; + + if (!expectedTimes) { + debug$4('Route has been called at least once, and no expectation of more set:', identifier); + return true; + } + + var actualTimes = _this.filterCalls(identifier).length; + + debug$4("Route called ".concat(actualTimes, " times:"), identifier); + + if (expectedTimes > actualTimes) { + debug$4("Route called ".concat(actualTimes, " times, but expected ").concat(expectedTimes, ":"), identifier); + console.warn("Warning: ".concat(identifier, " only called ").concat(actualTimes, " times, but ").concat(expectedTimes, " expected")); // eslint-disable-line + + return false; + } else { + return true; + } + }).every(function (isDone) { + return isDone; + }); + setDebugNamespace$1(); + setDebugPhase$2(); + return result; + }); + var inspecting = FetchMock$2; + + var debug$5 = debug_1.debug; + + + + + + + + + + var FetchMock$3 = Object.assign({}, fetchHandler, setUpAndTearDown, inspecting); + + FetchMock$3.addMatcher = function (matcher) { + Route_1.addMatcher(matcher); + }; + + FetchMock$3.config = { + fallbackToNetwork: false, + includeContentLength: true, + sendAsJson: true, + warnOnFallback: true, + overwriteRoutes: undefined + }; + + FetchMock$3.createInstance = function () { + var _this = this; + + debug$5('Creating fetch-mock instance'); + var instance = Object.create(FetchMock$3); + instance._uncompiledRoutes = (this._uncompiledRoutes || []).slice(); + instance.routes = instance._uncompiledRoutes.map(function (config) { + return _this.compileRoute(config); + }); + instance.fallbackResponse = this.fallbackResponse || undefined; + instance.config = Object.assign({}, this.config || FetchMock$3.config); + instance._calls = []; + instance._holdingPromises = []; + instance.bindMethods(); + return instance; + }; + + FetchMock$3.compileRoute = function (config) { + return new Route_1(config, this); + }; + + FetchMock$3.bindMethods = function () { + this.fetchHandler = FetchMock$3.fetchHandler.bind(this); + this.reset = this.restore = FetchMock$3.reset.bind(this); + this.resetHistory = FetchMock$3.resetHistory.bind(this); + this.resetBehavior = FetchMock$3.resetBehavior.bind(this); + }; + + FetchMock$3.sandbox = function () { + debug$5('Creating sandboxed fetch-mock instance'); // this construct allows us to create a fetch-mock instance which is also + // a callable function, while circumventing circularity when defining the + // object that this function should be bound to + + var fetchMockProxy = function fetchMockProxy(url, options) { + return sandbox.fetchHandler(url, options); + }; + + var sandbox = Object.assign(fetchMockProxy, // Ensures that the entire returned object is a callable function + FetchMock$3, // prototype methods + this.createInstance(), // instance data + { + Headers: this.config.Headers, + Request: this.config.Request, + Response: this.config.Response + }); + sandbox.bindMethods(); + sandbox.isSandbox = true; + sandbox["default"] = sandbox; + return sandbox; + }; + + FetchMock$3.getOption = function (name) { + var route = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + return name in route ? route[name] : this.config[name]; + }; + + var lib$k = FetchMock$3; + + var statusTextMap = { + 100: 'Continue', + 101: 'Switching Protocols', + 102: 'Processing', + 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: 'Unordered Collection', + 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' + }; + var statusText = statusTextMap; + + var theGlobal = typeof window !== 'undefined' ? window : self; + + var setUrlImplementation = requestUtils.setUrlImplementation; + + setUrlImplementation(theGlobal.URL); + lib$k.global = theGlobal; + lib$k.statusTextMap = statusText; + lib$k.config = Object.assign(lib$k.config, { + Promise: theGlobal.Promise, + Request: theGlobal.Request, + Response: theGlobal.Response, + Headers: theGlobal.Headers + }); + var client = lib$k.createInstance(); + + lib$j.transform('code', { + plugins: ['transform-runtime'] + }); + + var clientLegacy = client; + + return clientLegacy; + +}))); diff --git a/es5/client-legacy.js b/es5/client-legacy.js new file mode 100644 index 00000000..3b8fca1f --- /dev/null +++ b/es5/client-legacy.js @@ -0,0 +1,7 @@ +"use strict"; + +require('@babel/core').transform('code', { + plugins: ['transform-runtime'] +}); + +module.exports = require('./client'); \ No newline at end of file diff --git a/es5/client.js b/es5/client.js new file mode 100644 index 00000000..914dd641 --- /dev/null +++ b/es5/client.js @@ -0,0 +1,21 @@ +"use strict"; + +var FetchMock = require('./lib/index'); + +var statusTextMap = require('./lib/status-text'); + +var theGlobal = typeof window !== 'undefined' ? window : self; + +var _require = require('./lib/request-utils'), + setUrlImplementation = _require.setUrlImplementation; + +setUrlImplementation(theGlobal.URL); +FetchMock.global = theGlobal; +FetchMock.statusTextMap = statusTextMap; +FetchMock.config = Object.assign(FetchMock.config, { + Promise: theGlobal.Promise, + Request: theGlobal.Request, + Response: theGlobal.Response, + Headers: theGlobal.Headers +}); +module.exports = FetchMock.createInstance(); \ No newline at end of file diff --git a/es5/lib/debug.js b/es5/lib/debug.js new file mode 100644 index 00000000..e0d05ed4 --- /dev/null +++ b/es5/lib/debug.js @@ -0,0 +1,33 @@ +"use strict"; + +var debug = require('debug'); + +var debugFunc; +var phase = 'default'; +var namespace = ''; + +var newDebug = function newDebug() { + debugFunc = namespace ? debug("fetch-mock:".concat(phase, ":").concat(namespace)) : debug("fetch-mock:".concat(phase)); +}; + +var newDebugSandbox = function newDebugSandbox(ns) { + return debug("fetch-mock:".concat(phase, ":").concat(ns)); +}; + +newDebug(); +module.exports = { + debug: function debug() { + debugFunc.apply(void 0, arguments); + }, + setDebugNamespace: function setDebugNamespace(str) { + namespace = str; + newDebug(); + }, + setDebugPhase: function setDebugPhase(str) { + phase = str || 'default'; + newDebug(); + }, + getDebug: function getDebug(namespace) { + return newDebugSandbox(namespace); + } +}; \ No newline at end of file diff --git a/es5/lib/fetch-handler.js b/es5/lib/fetch-handler.js new file mode 100755 index 00000000..bdf52b49 --- /dev/null +++ b/es5/lib/fetch-handler.js @@ -0,0 +1,482 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); + +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); + +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); + +var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); + +var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")); + +var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); + +var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); + +var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); + +var _wrapNativeSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/wrapNativeSuper")); + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + +var _require = require('./debug'), + debug = _require.debug, + setDebugPhase = _require.setDebugPhase, + getDebug = _require.getDebug; + +var responseBuilder = require('./response-builder'); + +var requestUtils = require('./request-utils'); + +var FetchMock = {}; // see https://heycam.github.io/webidl/#aborterror for the standardised interface +// Note that this differs slightly from node-fetch + +var AbortError = /*#__PURE__*/function (_Error) { + (0, _inherits2["default"])(AbortError, _Error); + + var _super = _createSuper(AbortError); + + function AbortError() { + var _this; + + (0, _classCallCheck2["default"])(this, AbortError); + _this = _super.apply(this, arguments); + _this.name = 'AbortError'; + _this.message = 'The operation was aborted.'; // Do not include this class in the stacktrace + + if (Error.captureStackTrace) { + Error.captureStackTrace((0, _assertThisInitialized2["default"])(_this), _this.constructor); + } + + return _this; + } + + return AbortError; +}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error)); // Patch native fetch to avoid "NotSupportedError:ReadableStream uploading is not supported" in Safari. +// See also https://github.com/wheresrhys/fetch-mock/issues/584 +// See also https://stackoverflow.com/a/50952018/1273406 + + +var patchNativeFetchForSafari = function patchNativeFetchForSafari(nativeFetch) { + // Try to patch fetch only on Safari + if (typeof navigator === 'undefined' || !navigator.vendor || navigator.vendor !== 'Apple Computer, Inc.') { + return nativeFetch; + } // It seems the code is working on Safari thus patch native fetch to avoid the error. + + + return /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(request) { + var method, body, cache, credentials, headers, integrity, mode, redirect, referrer, init; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + method = request.method; + + if (['POST', 'PUT', 'PATCH'].includes(method)) { + _context.next = 3; + break; + } + + return _context.abrupt("return", nativeFetch(request)); + + case 3: + _context.next = 5; + return request.clone().text(); + + case 5: + body = _context.sent; + cache = request.cache, credentials = request.credentials, headers = request.headers, integrity = request.integrity, mode = request.mode, redirect = request.redirect, referrer = request.referrer; + init = { + body: body, + cache: cache, + credentials: credentials, + headers: headers, + integrity: integrity, + mode: mode, + redirect: redirect, + referrer: referrer, + method: method + }; + return _context.abrupt("return", nativeFetch(request.url, init)); + + case 9: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + + return function (_x) { + return _ref.apply(this, arguments); + }; + }(); +}; + +var resolve = /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(_ref3, url, options, request) { + var response, _ref3$responseIsFetch, responseIsFetch, debug; + + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + response = _ref3.response, _ref3$responseIsFetch = _ref3.responseIsFetch, responseIsFetch = _ref3$responseIsFetch === void 0 ? false : _ref3$responseIsFetch; + debug = getDebug('resolve()'); + debug('Recursively resolving function and promise responses'); // We want to allow things like + // - function returning a Promise for a response + // - delaying (using a timeout Promise) a function's execution to generate + // a response + // Because of this we can't safely check for function before Promisey-ness, + // or vice versa. So to keep it DRY, and flexible, we keep trying until we + // have something that looks like neither Promise nor function + + case 3: + if (!true) { + _context2.next = 31; + break; + } + + if (!(typeof response === 'function')) { + _context2.next = 18; + break; + } + + debug(' Response is a function'); // in the case of falling back to the network we need to make sure we're using + // the original Request instance, not our normalised url + options + + if (!responseIsFetch) { + _context2.next = 14; + break; + } + + if (!request) { + _context2.next = 10; + break; + } + + debug(' -> Calling fetch with Request instance'); + return _context2.abrupt("return", response(request)); + + case 10: + debug(' -> Calling fetch with url and options'); + return _context2.abrupt("return", response(url, options)); + + case 14: + debug(' -> Calling response function'); + response = response(url, options, request); + + case 16: + _context2.next = 29; + break; + + case 18: + if (!(typeof response.then === 'function')) { + _context2.next = 26; + break; + } + + debug(' Response is a promise'); + debug(' -> Resolving promise'); + _context2.next = 23; + return response; + + case 23: + response = _context2.sent; + _context2.next = 29; + break; + + case 26: + debug(' Response is not a function or a promise'); + debug(' -> Exiting response resolution recursion'); + return _context2.abrupt("return", response); + + case 29: + _context2.next = 3; + break; + + case 31: + case "end": + return _context2.stop(); + } + } + }, _callee2); + })); + + return function resolve(_x2, _x3, _x4, _x5) { + return _ref2.apply(this, arguments); + }; +}(); + +FetchMock.needsAsyncBodyExtraction = function (_ref4) { + var request = _ref4.request; + return request && this.routes.some(function (_ref5) { + var usesBody = _ref5.usesBody; + return usesBody; + }); +}; + +FetchMock.fetchHandler = function (url, options) { + setDebugPhase('handle'); + var debug = getDebug('fetchHandler()'); + debug('fetch called with:', url, options); + var normalizedRequest = requestUtils.normalizeRequest(url, options, this.config.Request); + debug('Request normalised'); + debug(' url', normalizedRequest.url); + debug(' options', normalizedRequest.options); + debug(' request', normalizedRequest.request); + debug(' signal', normalizedRequest.signal); + + if (this.needsAsyncBodyExtraction(normalizedRequest)) { + debug('Need to wait for Body to be streamed before calling router: switching to async mode'); + return this._extractBodyThenHandle(normalizedRequest); + } + + return this._fetchHandler(normalizedRequest); +}; + +FetchMock._extractBodyThenHandle = /*#__PURE__*/function () { + var _ref6 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(normalizedRequest) { + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return normalizedRequest.options.body; + + case 2: + normalizedRequest.options.body = _context3.sent; + return _context3.abrupt("return", this._fetchHandler(normalizedRequest)); + + case 4: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); + + return function (_x6) { + return _ref6.apply(this, arguments); + }; +}(); + +FetchMock._fetchHandler = function (_ref7) { + var _this2 = this; + + var url = _ref7.url, + options = _ref7.options, + request = _ref7.request, + signal = _ref7.signal; + + var _this$executeRouter = this.executeRouter(url, options, request), + route = _this$executeRouter.route, + callLog = _this$executeRouter.callLog; + + this.recordCall(callLog); // this is used to power the .flush() method + + var done; + + this._holdingPromises.push(new this.config.Promise(function (res) { + return done = res; + })); // wrapped in this promise to make sure we respect custom Promise + // constructors defined by the user + + + return new this.config.Promise(function (res, rej) { + if (signal) { + debug('signal exists - enabling fetch abort'); + + var abort = function abort() { + debug('aborting fetch'); // note that DOMException is not available in node.js; + // even node-fetch uses a custom error class: + // https://github.com/bitinn/node-fetch/blob/master/src/abort-error.js + + rej(typeof DOMException !== 'undefined' ? new DOMException('The operation was aborted.', 'AbortError') : new AbortError()); + done(); + }; + + if (signal.aborted) { + debug('signal is already aborted - aborting the fetch'); + abort(); + } + + signal.addEventListener('abort', abort); + } + + _this2.generateResponse({ + route: route, + url: url, + options: options, + request: request, + callLog: callLog + }).then(res, rej).then(done, done).then(function () { + setDebugPhase(); + }); + }); +}; + +FetchMock.fetchHandler.isMock = true; + +FetchMock.executeRouter = function (url, options, request) { + var debug = getDebug('executeRouter()'); + var callLog = { + url: url, + options: options, + request: request, + isUnmatched: true + }; + debug("Attempting to match request to a route"); + + if (this.getOption('fallbackToNetwork') === 'always') { + debug(' Configured with fallbackToNetwork=always - passing through to fetch'); + return { + route: { + response: this.getNativeFetch(), + responseIsFetch: true + } // BUG - this callLog never used to get sent. Discovered the bug + // but can't fix outside a major release as it will potentially + // cause too much disruption + // + // callLog, + + }; + } + + var route = this.router(url, options, request); + + if (route) { + debug(' Matching route found'); + return { + route: route, + callLog: { + url: url, + options: options, + request: request, + identifier: route.identifier + } + }; + } + + if (this.getOption('warnOnFallback')) { + console.warn("Unmatched ".concat(options && options.method || 'GET', " to ").concat(url)); // eslint-disable-line + } + + if (this.fallbackResponse) { + debug(' No matching route found - using fallbackResponse'); + return { + route: { + response: this.fallbackResponse + }, + callLog: callLog + }; + } + + if (!this.getOption('fallbackToNetwork')) { + throw new Error("fetch-mock: No fallback response defined for ".concat(options && options.method || 'GET', " to ").concat(url)); + } + + debug(' Configured to fallbackToNetwork - passing through to fetch'); + return { + route: { + response: this.getNativeFetch(), + responseIsFetch: true + }, + callLog: callLog + }; +}; + +FetchMock.generateResponse = /*#__PURE__*/function () { + var _ref8 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(_ref9) { + var route, url, options, request, _ref9$callLog, callLog, debug, response, _responseBuilder, _responseBuilder2, realResponse, finalResponse; + + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + route = _ref9.route, url = _ref9.url, options = _ref9.options, request = _ref9.request, _ref9$callLog = _ref9.callLog, callLog = _ref9$callLog === void 0 ? {} : _ref9$callLog; + debug = getDebug('generateResponse()'); + _context4.next = 4; + return resolve(route, url, options, request); + + case 4: + response = _context4.sent; + + if (!(response["throws"] && typeof response !== 'function')) { + _context4.next = 8; + break; + } + + debug('response.throws is defined - throwing an error'); + throw response["throws"]; + + case 8: + if (!this.config.Response.prototype.isPrototypeOf(response)) { + _context4.next = 12; + break; + } + + debug('response is already a Response instance - returning it'); + callLog.response = response; + return _context4.abrupt("return", response); + + case 12: + // finally, if we need to convert config into a response, we do it + _responseBuilder = responseBuilder({ + url: url, + responseConfig: response, + fetchMock: this, + route: route + }), _responseBuilder2 = (0, _slicedToArray2["default"])(_responseBuilder, 2), realResponse = _responseBuilder2[0], finalResponse = _responseBuilder2[1]; + callLog.response = realResponse; + return _context4.abrupt("return", finalResponse); + + case 15: + case "end": + return _context4.stop(); + } + } + }, _callee4, this); + })); + + return function (_x7) { + return _ref8.apply(this, arguments); + }; +}(); + +FetchMock.router = function (url, options, request) { + var route = this.routes.find(function (route, i) { + debug("Trying to match route ".concat(i)); + return route.matcher(url, options, request); + }); + + if (route) { + return route; + } +}; + +FetchMock.getNativeFetch = function () { + var func = this.realFetch || this.isSandbox && this.config.fetch; + + if (!func) { + throw new Error('fetch-mock: Falling back to network only available on global fetch-mock, or by setting config.fetch on sandboxed fetch-mock'); + } + + return patchNativeFetchForSafari(func); +}; + +FetchMock.recordCall = function (obj) { + debug('Recording fetch call', obj); + + if (obj) { + this._calls.push(obj); + } +}; + +module.exports = FetchMock; \ No newline at end of file diff --git a/es5/lib/index.js b/es5/lib/index.js new file mode 100644 index 00000000..8762f25b --- /dev/null +++ b/es5/lib/index.js @@ -0,0 +1,84 @@ +"use strict"; + +var _require = require('./debug'), + debug = _require.debug; + +var setUpAndTearDown = require('./set-up-and-tear-down'); + +var fetchHandler = require('./fetch-handler'); + +var inspecting = require('./inspecting'); + +var Route = require('../Route'); + +var FetchMock = Object.assign({}, fetchHandler, setUpAndTearDown, inspecting); + +FetchMock.addMatcher = function (matcher) { + Route.addMatcher(matcher); +}; + +FetchMock.config = { + fallbackToNetwork: false, + includeContentLength: true, + sendAsJson: true, + warnOnFallback: true, + overwriteRoutes: undefined +}; + +FetchMock.createInstance = function () { + var _this = this; + + debug('Creating fetch-mock instance'); + var instance = Object.create(FetchMock); + instance._uncompiledRoutes = (this._uncompiledRoutes || []).slice(); + instance.routes = instance._uncompiledRoutes.map(function (config) { + return _this.compileRoute(config); + }); + instance.fallbackResponse = this.fallbackResponse || undefined; + instance.config = Object.assign({}, this.config || FetchMock.config); + instance._calls = []; + instance._holdingPromises = []; + instance.bindMethods(); + return instance; +}; + +FetchMock.compileRoute = function (config) { + return new Route(config, this); +}; + +FetchMock.bindMethods = function () { + this.fetchHandler = FetchMock.fetchHandler.bind(this); + this.reset = this.restore = FetchMock.reset.bind(this); + this.resetHistory = FetchMock.resetHistory.bind(this); + this.resetBehavior = FetchMock.resetBehavior.bind(this); +}; + +FetchMock.sandbox = function () { + debug('Creating sandboxed fetch-mock instance'); // this construct allows us to create a fetch-mock instance which is also + // a callable function, while circumventing circularity when defining the + // object that this function should be bound to + + var fetchMockProxy = function fetchMockProxy(url, options) { + return sandbox.fetchHandler(url, options); + }; + + var sandbox = Object.assign(fetchMockProxy, // Ensures that the entire returned object is a callable function + FetchMock, // prototype methods + this.createInstance(), // instance data + { + Headers: this.config.Headers, + Request: this.config.Request, + Response: this.config.Response + }); + sandbox.bindMethods(); + sandbox.isSandbox = true; + sandbox["default"] = sandbox; + return sandbox; +}; + +FetchMock.getOption = function (name) { + var route = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + return name in route ? route[name] : this.config[name]; +}; + +module.exports = FetchMock; \ No newline at end of file diff --git a/es5/lib/inspecting.js b/es5/lib/inspecting.js new file mode 100644 index 00000000..c203986e --- /dev/null +++ b/es5/lib/inspecting.js @@ -0,0 +1,278 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); + +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); + +var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); + +var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")); + +var _require = require('./debug'), + setDebugPhase = _require.setDebugPhase, + setDebugNamespace = _require.setDebugNamespace, + debug = _require.debug; + +var _require2 = require('./request-utils'), + normalizeUrl = _require2.normalizeUrl; + +var Route = require('../Route'); + +var FetchMock = {}; + +var isName = function isName(nameOrMatcher) { + return typeof nameOrMatcher === 'string' && /^[\da-zA-Z\-]+$/.test(nameOrMatcher); +}; + +var filterCallsWithMatcher = function filterCallsWithMatcher(matcher) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var calls = arguments.length > 2 ? arguments[2] : undefined; + + var _Route = new Route([Object.assign({ + matcher: matcher, + response: 'ok' + }, options)], this); + + matcher = _Route.matcher; + return calls.filter(function (_ref) { + var url = _ref.url, + options = _ref.options; + return matcher(normalizeUrl(url), options); + }); +}; + +var formatDebug = function formatDebug(func) { + return function () { + setDebugPhase('inspect'); + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var result = func.call.apply(func, [this].concat(args)); + setDebugPhase(); + return result; + }; +}; + +var callObjToArray = function callObjToArray(obj) { + if (!obj) { + return undefined; + } + + var url = obj.url, + options = obj.options, + request = obj.request, + identifier = obj.identifier, + isUnmatched = obj.isUnmatched, + response = obj.response; + var arr = [url, options]; + arr.request = request; + arr.identifier = identifier; + arr.isUnmatched = isUnmatched; + arr.response = response; + return arr; +}; + +FetchMock.filterCalls = function (nameOrMatcher, options) { + debug('Filtering fetch calls'); + var calls = this._calls; + var matcher = '*'; + + if ([true, 'matched'].includes(nameOrMatcher)) { + debug("Filter provided is ".concat(nameOrMatcher, ". Returning matched calls only")); + calls = calls.filter(function (_ref2) { + var isUnmatched = _ref2.isUnmatched; + return !isUnmatched; + }); + } else if ([false, 'unmatched'].includes(nameOrMatcher)) { + debug("Filter provided is ".concat(nameOrMatcher, ". Returning unmatched calls only")); + calls = calls.filter(function (_ref3) { + var isUnmatched = _ref3.isUnmatched; + return isUnmatched; + }); + } else if (typeof nameOrMatcher === 'undefined') { + debug("Filter provided is undefined. Returning all calls"); + calls = calls; + } else if (isName(nameOrMatcher)) { + debug("Filter provided, looks like the name of a named route. Returning only calls handled by that route"); + calls = calls.filter(function (_ref4) { + var identifier = _ref4.identifier; + return identifier === nameOrMatcher; + }); + } else { + matcher = nameOrMatcher === '*' ? '*' : normalizeUrl(nameOrMatcher); + + if (this.routes.some(function (_ref5) { + var identifier = _ref5.identifier; + return identifier === matcher; + })) { + debug("Filter provided, ".concat(nameOrMatcher, ", identifies a route. Returning only calls handled by that route")); + calls = calls.filter(function (call) { + return call.identifier === matcher; + }); + } + } + + if ((options || matcher !== '*') && calls.length) { + if (typeof options === 'string') { + options = { + method: options + }; + } + + debug('Compiling filter and options to route in order to filter all calls', nameOrMatcher); + calls = filterCallsWithMatcher.call(this, matcher, options, calls); + } + + debug("Retrieved ".concat(calls.length, " calls")); + return calls.map(callObjToArray); +}; + +FetchMock.calls = formatDebug(function (nameOrMatcher, options) { + debug('retrieving matching calls'); + return this.filterCalls(nameOrMatcher, options); +}); +FetchMock.lastCall = formatDebug(function (nameOrMatcher, options) { + debug('retrieving last matching call'); + return (0, _toConsumableArray2["default"])(this.filterCalls(nameOrMatcher, options)).pop(); +}); +FetchMock.lastUrl = formatDebug(function (nameOrMatcher, options) { + debug('retrieving url of last matching call'); + return (this.lastCall(nameOrMatcher, options) || [])[0]; +}); +FetchMock.lastOptions = formatDebug(function (nameOrMatcher, options) { + debug('retrieving options of last matching call'); + return (this.lastCall(nameOrMatcher, options) || [])[1]; +}); +FetchMock.lastResponse = formatDebug(function (nameOrMatcher, options) { + debug('retrieving respose of last matching call'); + console.warn("When doing all the following:\n- using node-fetch\n- responding with a real network response (using spy() or fallbackToNetwork)\n- using `fetchMock.LastResponse()`\n- awaiting the body content\n... the response will hang unless your source code also awaits the response body.\nThis is an unavoidable consequence of the nodejs implementation of streams.\n"); + var response = (this.lastCall(nameOrMatcher, options) || []).response; + + try { + var clonedResponse = response.clone(); + return clonedResponse; + } catch (err) { + Object.entries(response._fmResults).forEach(function (_ref6) { + var _ref7 = (0, _slicedToArray2["default"])(_ref6, 2), + name = _ref7[0], + result = _ref7[1]; + + response[name] = function () { + return result; + }; + }); + return response; + } +}); +FetchMock.called = formatDebug(function (nameOrMatcher, options) { + debug('checking if matching call was made'); + return Boolean(this.filterCalls(nameOrMatcher, options).length); +}); +FetchMock.flush = formatDebug( /*#__PURE__*/function () { + var _ref8 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(waitForResponseMethods) { + var queuedPromises; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + setDebugNamespace('flush'); + debug("flushing all fetch calls. ".concat(waitForResponseMethods ? '' : 'Not ', "waiting for response bodies to complete download")); + queuedPromises = this._holdingPromises; + this._holdingPromises = []; + debug("".concat(queuedPromises.length, " fetch calls to be awaited")); + _context.next = 7; + return Promise.all(queuedPromises); + + case 7: + debug("All fetch calls have completed"); + + if (!(waitForResponseMethods && this._holdingPromises.length)) { + _context.next = 13; + break; + } + + debug("Awaiting all fetch bodies to download"); + _context.next = 12; + return this.flush(waitForResponseMethods); + + case 12: + debug("All fetch bodies have completed downloading"); + + case 13: + setDebugNamespace(); + + case 14: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + return function (_x) { + return _ref8.apply(this, arguments); + }; +}()); +FetchMock.done = formatDebug(function (nameOrMatcher) { + var _this = this; + + setDebugPhase('inspect'); + setDebugNamespace('done'); + debug('Checking to see if expected calls have been made'); + var routesToCheck; + + if (nameOrMatcher && typeof nameOrMatcher !== 'boolean') { + debug('Checking to see if expected calls have been made for single route:', nameOrMatcher); + routesToCheck = [{ + identifier: nameOrMatcher + }]; + } else { + debug('Checking to see if expected calls have been made for all routes'); + routesToCheck = this.routes; + } // Can't use array.every because would exit after first failure, which would + // break the logging + + + var result = routesToCheck.map(function (_ref9) { + var identifier = _ref9.identifier; + + if (!_this.called(identifier)) { + debug('No calls made for route:', identifier); + console.warn("Warning: ".concat(identifier, " not called")); // eslint-disable-line + + return false; + } + + var expectedTimes = (_this.routes.find(function (r) { + return r.identifier === identifier; + }) || {}).repeat; + + if (!expectedTimes) { + debug('Route has been called at least once, and no expectation of more set:', identifier); + return true; + } + + var actualTimes = _this.filterCalls(identifier).length; + + debug("Route called ".concat(actualTimes, " times:"), identifier); + + if (expectedTimes > actualTimes) { + debug("Route called ".concat(actualTimes, " times, but expected ").concat(expectedTimes, ":"), identifier); + console.warn("Warning: ".concat(identifier, " only called ").concat(actualTimes, " times, but ").concat(expectedTimes, " expected")); // eslint-disable-line + + return false; + } else { + return true; + } + }).every(function (isDone) { + return isDone; + }); + setDebugNamespace(); + setDebugPhase(); + return result; +}); +module.exports = FetchMock; \ No newline at end of file diff --git a/es5/lib/request-utils.js b/es5/lib/request-utils.js new file mode 100644 index 00000000..7acf9927 --- /dev/null +++ b/es5/lib/request-utils.js @@ -0,0 +1,171 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof")); + +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); + +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); + +var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); + +var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); + +var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")); + +var URL; // https://stackoverflow.com/a/19709846/308237 +// split, URL constructor does not support protocol-relative urls + +var absoluteUrlRX = new RegExp('^[a-z]+://', 'i'); +var protocolRelativeUrlRX = new RegExp('^//', 'i'); + +var headersToArray = function headersToArray(headers) { + // node-fetch 1 Headers + if (typeof headers.raw === 'function') { + return Object.entries(headers.raw()); + } else if (headers[Symbol.iterator]) { + return (0, _toConsumableArray2["default"])(headers); + } else { + return Object.entries(headers); + } +}; + +var zipObject = function zipObject(entries) { + return entries.reduce(function (obj, _ref) { + var _ref2 = (0, _slicedToArray2["default"])(_ref, 2), + key = _ref2[0], + val = _ref2[1]; + + return Object.assign(obj, (0, _defineProperty2["default"])({}, key, val)); + }, {}); +}; + +var normalizeUrl = function normalizeUrl(url) { + if (typeof url === 'function' || url instanceof RegExp || /^(begin|end|glob|express|path)\:/.test(url)) { + return url; + } + + if (absoluteUrlRX.test(url)) { + var u = new URL(url); + return u.href; + } else if (protocolRelativeUrlRX.test(url)) { + var _u = new URL(url, 'http://dummy'); + + return _u.href; + } else { + var _u2 = new URL(url, 'http://dummy'); + + return _u2.pathname + _u2.search; + } +}; + +var extractBody = /*#__PURE__*/function () { + var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(request) { + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + + if (!('body' in request)) { + _context.next = 3; + break; + } + + return _context.abrupt("return", request.body.toString()); + + case 3: + return _context.abrupt("return", request.clone().text()); + + case 6: + _context.prev = 6; + _context.t0 = _context["catch"](0); + + case 8: + case "end": + return _context.stop(); + } + } + }, _callee, null, [[0, 6]]); + })); + + return function extractBody(_x) { + return _ref3.apply(this, arguments); + }; +}(); + +module.exports = { + setUrlImplementation: function setUrlImplementation(it) { + URL = it; + }, + normalizeRequest: function normalizeRequest(url, options, Request) { + if (Request.prototype.isPrototypeOf(url)) { + var derivedOptions = { + method: url.method + }; + var body = extractBody(url); + + if (typeof body !== 'undefined') { + derivedOptions.body = body; + } + + var normalizedRequestObject = { + url: normalizeUrl(url.url), + options: Object.assign(derivedOptions, options), + request: url, + signal: options && options.signal || url.signal + }; + var headers = headersToArray(url.headers); + + if (headers.length) { + normalizedRequestObject.options.headers = zipObject(headers); + } + + return normalizedRequestObject; + } else if (typeof url === 'string' || // horrible URL object duck-typing + (0, _typeof2["default"])(url) === 'object' && 'href' in url) { + return { + url: normalizeUrl(url), + options: options, + signal: options && options.signal + }; + } else if ((0, _typeof2["default"])(url) === 'object') { + throw new TypeError('fetch-mock: Unrecognised Request object. Read the Config and Installation sections of the docs'); + } else { + throw new TypeError('fetch-mock: Invalid arguments passed to fetch'); + } + }, + normalizeUrl: normalizeUrl, + getPath: function getPath(url) { + var u = absoluteUrlRX.test(url) ? new URL(url) : new URL(url, 'http://dummy'); + return u.pathname; + }, + getQuery: function getQuery(url) { + var u = absoluteUrlRX.test(url) ? new URL(url) : new URL(url, 'http://dummy'); + return u.search ? u.search.substr(1) : ''; + }, + headers: { + normalize: function normalize(headers) { + return zipObject(headersToArray(headers)); + }, + toLowerCase: function toLowerCase(headers) { + return Object.keys(headers).reduce(function (obj, k) { + obj[k.toLowerCase()] = headers[k]; + return obj; + }, {}); + }, + equal: function equal(actualHeader, expectedHeader) { + actualHeader = Array.isArray(actualHeader) ? actualHeader : [actualHeader]; + expectedHeader = Array.isArray(expectedHeader) ? expectedHeader : [expectedHeader]; + + if (actualHeader.length !== expectedHeader.length) { + return false; + } + + return actualHeader.every(function (val, i) { + return val === expectedHeader[i]; + }); + } + } +}; \ No newline at end of file diff --git a/es5/lib/response-builder.js b/es5/lib/response-builder.js new file mode 100644 index 00000000..2c512dd7 --- /dev/null +++ b/es5/lib/response-builder.js @@ -0,0 +1,209 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof")); + +var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); + +var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); + +var _require = require('./debug'), + getDebug = _require.getDebug; + +var responseConfigProps = ['body', 'headers', 'throws', 'status', 'redirectUrl']; + +var ResponseBuilder = /*#__PURE__*/function () { + function ResponseBuilder(options) { + (0, _classCallCheck2["default"])(this, ResponseBuilder); + this.debug = getDebug('ResponseBuilder()'); + this.debug('Response builder created with options', options); + Object.assign(this, options); + } + + (0, _createClass2["default"])(ResponseBuilder, [{ + key: "exec", + value: function exec() { + this.debug('building response'); + this.normalizeResponseConfig(); + this.constructFetchOpts(); + this.constructResponseBody(); + var realResponse = new this.fetchMock.config.Response(this.body, this.options); + var proxyResponse = this.buildObservableResponse(realResponse); + return [realResponse, proxyResponse]; + } + }, { + key: "sendAsObject", + value: function sendAsObject() { + var _this = this; + + if (responseConfigProps.some(function (prop) { + return _this.responseConfig[prop]; + })) { + if (Object.keys(this.responseConfig).every(function (key) { + return responseConfigProps.includes(key); + })) { + return false; + } else { + return true; + } + } else { + return true; + } + } + }, { + key: "normalizeResponseConfig", + value: function normalizeResponseConfig() { + // If the response config looks like a status, start to generate a simple response + if (typeof this.responseConfig === 'number') { + this.debug('building response using status', this.responseConfig); + this.responseConfig = { + status: this.responseConfig + }; // If the response config is not an object, or is an object that doesn't use + // any reserved properties, assume it is meant to be the body of the response + } else if (typeof this.responseConfig === 'string' || this.sendAsObject()) { + this.debug('building text response from', this.responseConfig); + this.responseConfig = { + body: this.responseConfig + }; + } + } + }, { + key: "validateStatus", + value: function validateStatus(status) { + if (!status) { + this.debug('No status provided. Defaulting to 200'); + return 200; + } + + if (typeof status === 'number' && parseInt(status, 10) !== status && status >= 200 || status < 600) { + this.debug('Valid status provided', status); + return status; + } + + throw new TypeError("fetch-mock: Invalid status ".concat(status, " passed on response object.\nTo respond with a JSON object that has status as a property assign the object to body\ne.g. {\"body\": {\"status: \"registered\"}}")); + } + }, { + key: "constructFetchOpts", + value: function constructFetchOpts() { + this.options = this.responseConfig.options || {}; + this.options.url = this.responseConfig.redirectUrl || this.url; + this.options.status = this.validateStatus(this.responseConfig.status); + this.options.statusText = this.fetchMock.statusTextMap[String(this.options.status)]; // Set up response headers. The empty object is to cope with + // new Headers(undefined) throwing in Chrome + // https://code.google.com/p/chromium/issues/detail?id=335871 + + this.options.headers = new this.fetchMock.config.Headers(this.responseConfig.headers || {}); + } + }, { + key: "getOption", + value: function getOption(name) { + return this.fetchMock.getOption(name, this.route); + } + }, { + key: "convertToJson", + value: function convertToJson() { + // convert to json if we need to + if (this.getOption('sendAsJson') && this.responseConfig.body != null && //eslint-disable-line + (0, _typeof2["default"])(this.body) === 'object') { + this.debug('Stringifying JSON response body'); + this.body = JSON.stringify(this.body); + + if (!this.options.headers.has('Content-Type')) { + this.options.headers.set('Content-Type', 'application/json'); + } + } + } + }, { + key: "setContentLength", + value: function setContentLength() { + // add a Content-Length header if we need to + if (this.getOption('includeContentLength') && typeof this.body === 'string' && !this.options.headers.has('Content-Length')) { + this.debug('Setting content-length header:', this.body.length.toString()); + this.options.headers.set('Content-Length', this.body.length.toString()); + } + } + }, { + key: "constructResponseBody", + value: function constructResponseBody() { + // start to construct the body + this.body = this.responseConfig.body; + this.convertToJson(); + this.setContentLength(); // On the server we need to manually construct the readable stream for the + // Response object (on the client this done automatically) + + if (this.Stream) { + this.debug('Creating response stream'); + var stream = new this.Stream.Readable(); + + if (this.body != null) { + //eslint-disable-line + stream.push(this.body, 'utf-8'); + } + + stream.push(null); + this.body = stream; + } + + this.body = this.body; + } + }, { + key: "buildObservableResponse", + value: function buildObservableResponse(response) { + var _this2 = this; + + var fetchMock = this.fetchMock; + response._fmResults = {}; // Using a proxy means we can set properties that may not be writable on + // the original Response. It also means we can track the resolution of + // promises returned by res.json(), res.text() etc + + this.debug('Wrapping Response in ES proxy for observability'); + return new Proxy(response, { + get: function get(originalResponse, name) { + if (_this2.responseConfig.redirectUrl) { + if (name === 'url') { + _this2.debug('Retrieving redirect url', _this2.responseConfig.redirectUrl); + + return _this2.responseConfig.redirectUrl; + } + + if (name === 'redirected') { + _this2.debug('Retrieving redirected status', true); + + return true; + } + } + + if (typeof originalResponse[name] === 'function') { + _this2.debug('Wrapping body promises in ES proxies for observability'); + + return new Proxy(originalResponse[name], { + apply: function apply(func, thisArg, args) { + _this2.debug("Calling res.".concat(name)); + + var result = func.apply(response, args); + + if (result.then) { + fetchMock._holdingPromises.push(result["catch"](function () { + return null; + })); + + originalResponse._fmResults[name] = result; + } + + return result; + } + }); + } + + return originalResponse[name]; + } + }); + } + }]); + return ResponseBuilder; +}(); + +module.exports = function (options) { + return new ResponseBuilder(options).exec(); +}; \ No newline at end of file diff --git a/es5/lib/set-up-and-tear-down.js b/es5/lib/set-up-and-tear-down.js new file mode 100644 index 00000000..3ad7be24 --- /dev/null +++ b/es5/lib/set-up-and-tear-down.js @@ -0,0 +1,172 @@ +"use strict"; + +var _require = require('./debug'), + debug = _require.debug, + setDebugPhase = _require.setDebugPhase; + +var FetchMock = {}; + +FetchMock.mock = function () { + setDebugPhase('setup'); + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + if (args.length) { + this.addRoute(args); + } + + return this._mock(); +}; + +FetchMock.addRoute = function (uncompiledRoute) { + var _this = this; + + debug('Adding route', uncompiledRoute); + var route = this.compileRoute(uncompiledRoute); + var clashes = this.routes.filter(function (_ref) { + var identifier = _ref.identifier, + method = _ref.method; + var isMatch = typeof identifier === 'function' ? identifier === route.identifier : String(identifier) === String(route.identifier); + return isMatch && (!method || !route.method || method === route.method); + }); + + if (this.getOption('overwriteRoutes', route) === false || !clashes.length) { + this._uncompiledRoutes.push(uncompiledRoute); + + return this.routes.push(route); + } + + if (this.getOption('overwriteRoutes', route) === true) { + clashes.forEach(function (clash) { + var index = _this.routes.indexOf(clash); + + _this._uncompiledRoutes.splice(index, 1, uncompiledRoute); + + _this.routes.splice(index, 1, route); + }); + return this.routes; + } + + if (clashes.length) { + throw new Error('fetch-mock: Adding route with same name or matcher as existing route. See `overwriteRoutes` option.'); + } + + this._uncompiledRoutes.push(uncompiledRoute); + + this.routes.push(route); +}; + +FetchMock._mock = function () { + if (!this.isSandbox) { + // Do this here rather than in the constructor to ensure it's scoped to the test + this.realFetch = this.realFetch || this.global.fetch; + this.global.fetch = this.fetchHandler; + } + + setDebugPhase(); + return this; +}; + +FetchMock["catch"] = function (response) { + if (this.fallbackResponse) { + console.warn('calling fetchMock.catch() twice - are you sure you want to overwrite the previous fallback response'); // eslint-disable-line + } + + this.fallbackResponse = response || 'ok'; + return this._mock(); +}; + +FetchMock.spy = function (route) { + // even though ._mock() is called by .mock() and .catch() we still need to + // call it here otherwise .getNativeFetch() won't be able to use the reference + // to .realFetch that ._mock() sets up + this._mock(); + + return route ? this.mock(route, this.getNativeFetch()) : this["catch"](this.getNativeFetch()); +}; + +var defineShorthand = function defineShorthand(methodName, underlyingMethod, shorthandOptions) { + FetchMock[methodName] = function (matcher, response, options) { + return this[underlyingMethod](matcher, response, Object.assign(options || {}, shorthandOptions)); + }; +}; + +var defineGreedyShorthand = function defineGreedyShorthand(methodName, underlyingMethod) { + FetchMock[methodName] = function (response, options) { + return this[underlyingMethod]({}, response, options); + }; +}; + +defineShorthand('sticky', 'mock', { + sticky: true +}); +defineShorthand('once', 'mock', { + repeat: 1 +}); +defineGreedyShorthand('any', 'mock'); +defineGreedyShorthand('anyOnce', 'once'); +['get', 'post', 'put', 'delete', 'head', 'patch'].forEach(function (method) { + defineShorthand(method, 'mock', { + method: method + }); + defineShorthand("".concat(method, "Once"), 'once', { + method: method + }); + defineGreedyShorthand("".concat(method, "Any"), method); + defineGreedyShorthand("".concat(method, "AnyOnce"), "".concat(method, "Once")); +}); + +var mochaAsyncHookWorkaround = function mochaAsyncHookWorkaround(options) { + // HACK workaround for this https://github.com/mochajs/mocha/issues/4280 + // Note that it doesn't matter that we call it _before_ carrying out all + // the things resetBehavior does as everything in there is synchronous + if (typeof options === 'function') { + console.warn("Deprecated: Passing fetch-mock reset methods\ndirectly in as handlers for before/after test runner hooks.\nWrap in an arrow function instead e.g. `() => fetchMock.restore()`"); + options(); + } +}; + +var getRouteRemover = function getRouteRemover(_ref2) { + var removeStickyRoutes = _ref2.sticky; + return function (routes) { + return removeStickyRoutes ? [] : routes.filter(function (_ref3) { + var sticky = _ref3.sticky; + return sticky; + }); + }; +}; + +FetchMock.resetBehavior = function () { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + mochaAsyncHookWorkaround(options); + var removeRoutes = getRouteRemover(options); + this.routes = removeRoutes(this.routes); + this._uncompiledRoutes = removeRoutes(this._uncompiledRoutes); + + if (this.realFetch && !this.routes.length) { + this.global.fetch = this.realFetch; + this.realFetch = undefined; + } + + this.fallbackResponse = undefined; + return this; +}; + +FetchMock.resetHistory = function () { + this._calls = []; + this._holdingPromises = []; + this.routes.forEach(function (route) { + return route.reset && route.reset(); + }); + return this; +}; + +FetchMock.restore = FetchMock.reset = function (options) { + this.resetBehavior(options); + this.resetHistory(); + return this; +}; + +module.exports = FetchMock; \ No newline at end of file diff --git a/es5/lib/status-text.js b/es5/lib/status-text.js new file mode 100644 index 00000000..5f365664 --- /dev/null +++ b/es5/lib/status-text.js @@ -0,0 +1,67 @@ +"use strict"; + +var statusTextMap = { + 100: 'Continue', + 101: 'Switching Protocols', + 102: 'Processing', + 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: 'Unordered Collection', + 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' +}; +module.exports = statusTextMap; \ No newline at end of file diff --git a/es5/server.js b/es5/server.js new file mode 100644 index 00000000..0dd86864 --- /dev/null +++ b/es5/server.js @@ -0,0 +1,39 @@ +"use strict"; + +// avoid circular dependency when using jest.mock() +var fetch; + +try { + // note that jest is not a global, but is injected somehow into + // the environment. So we can't be safe and check for global.jest + // Hence the try/catch + fetch = jest.requireActual('node-fetch'); //eslint-disable-line no-undef +} catch (e) { + fetch = require('node-fetch'); +} + +var Request = fetch.Request; +var Response = fetch.Response; +var Headers = fetch.Headers; + +var Stream = require('stream'); + +var FetchMock = require('./lib/index'); + +var http = require('http'); + +var _require = require('./lib/request-utils'), + setUrlImplementation = _require.setUrlImplementation; + +setUrlImplementation(require('whatwg-url').URL); +FetchMock.global = global; +FetchMock.statusTextMap = http.STATUS_CODES; +FetchMock.Stream = Stream; +FetchMock.config = Object.assign(FetchMock.config, { + Promise: Promise, + Request: Request, + Response: Response, + Headers: Headers, + fetch: fetch +}); +module.exports = FetchMock.createInstance(); \ No newline at end of file diff --git a/esm/client.d.ts b/esm/client.d.ts new file mode 100644 index 00000000..35d2bb99 --- /dev/null +++ b/esm/client.d.ts @@ -0,0 +1,697 @@ +// Project: https://github.com/wheresrhys/fetch-mock, http://www.wheresrhys.co.uk/fetch-mock +// Definitions by: Alexey Svetliakov +// Tamir Duberstein +// Risto Keravuori +// Chris Sinclair +// Matt Tennison +// Quentin Bouygues +// Fumiaki Matsushima +// Colin Doig +// Felix Chen +// Katsuya Hino +// +// Please note that I - wheresrys - don't use Typescript +// These types have ben copied in here as a convenience for (some of) +// fetch-mock's users +// If you are a Typescript user and find a problem in these types, please +// submit a PR +// +// TypeScript Version: 2.2 + +declare namespace fetchMock { + type MockRequest = Request | RequestInit; + + /** + * Mock matcher function + */ + type MockMatcherFunction = (url: string, opts: MockRequest) => boolean; + + + type MockMatcherUrl = string | RegExp; + + + /** + * Mock matcher. Can be one of following: + * string: Either + * * an exact url to match e.g. 'http://www.site.com/page.html' + * * if the string begins with a `^`, the string following the `^` must + * begin the url e.g. '^http://www.site.com' would match + * 'http://www.site.com' or 'http://www.site.com/page.html' + * * '*' to match any url + * RegExp: A regular expression to test the url against + * Function(url, opts): A function (returning a Boolean) that is passed the + * url and opts fetch() is called with (or, if fetch() was called with one, + * the Request instance) + */ + type MockMatcher = MockMatcherUrl | MockMatcherFunction; + + /** + * Inspection filter. Can be one of the following: + * boolean: + * * true retrieves all calls matched by fetch. + * fetchMock.MATCHED is an alias for true and may be used to make tests + * more readable. + * * false retrieves all calls not matched by fetch (i.e. those handled + * by catch() or spy(). fetchMock.UNMATCHED is an alias for false and + * may be used to make tests more readable. + * MockMatcher (routeIdentifier): + * All routes have an identifier: + * * If it’s a named route, the identifier is the route’s name + * * If the route is unnamed, the identifier is the matcher passed in to + * .mock() + * All calls that were handled by the route with the given identifier + * will be retrieved + * MockMatcher (matcher): + * Any matcher compatible with the mocking api can be passed in to filter + * the calls arbitrarily. + */ + type InspectionFilter = MockMatcher | boolean; + + /** + * Either an object compatible with the mocking api or a string specifying + * a http method to filter by. This will be used to filter the list of + * calls further. + */ + type InspectionOptions = MockOptions | string; + + /** + * Mock response object + */ + interface MockResponseObject { + /** + * Set the response body + */ + body?: string | {}; + + /** + * Set the response status + * @default 200 + */ + status?: number; + + /** + * Set the response headers. + */ + headers?: { [key: string]: string }; + + /** + * If this property is present then a Promise rejected with the value + * of throws is returned + */ + throws?: Error; + + /** + * The URL the response should be from (to imitate followed redirects + * - will set redirected: true on the response) + */ + redirectUrl?: string; + } + + /** + * Response: A Response instance - will be used unaltered + * number: Creates a response with this status + * string: Creates a 200 response with the string as the response body + * object: As long as the object is not a MockResponseObject it is + * converted into a json string and returned as the body of a 200 response + * If MockResponseObject was given then it's used to configure response + * Function(url, opts): A function that is passed the url and opts fetch() + * is called with and that returns any of the responses listed above + */ + type MockResponse = Response | Promise + | number | Promise + | string | Promise + | {} | Promise<{}> + | MockResponseObject | Promise; + + /** + * Mock response function + */ + type MockResponseFunction = (url: string, opts: MockRequest) => MockResponse; + + + /** + * Mock options object + */ + interface MockOptions { + /** + * A unique string naming the route. Used to subsequently retrieve + * references to the calls, grouped by name. + * @default matcher.toString() + * + * Note: If a non-unique name is provided no error will be thrown + * (because names are optional, auto-generated ones may legitimately + * clash) + */ + name?: string; + + /** + * http method to match + */ + method?: string; + + /** + * key/value map of headers to match + */ + headers?: { [key: string]: string | number }; + + /** + * key/value map of query strings to match, in any order + */ + query?: object; + + /** + * key/value map of express style path params to match + */ + params?: { [key: string]: string }; + + /** + * JSON serialisable object literal. Allowing any object for now + * But in typescript 3.7 will change to JSON + */ + body?: object; + + /** + * A function for arbitrary matching + */ + functionMatcher?: MockMatcherFunction; + + /** + * as specified above + */ + matcher?: MockMatcher; + + url?: MockMatcherUrl; + + /** + * This option allows for existing routes in a mock to be overwritten. + * It’s also possible to define multiple routes with ‘the same’ matcher. + * Default behaviour is to error + */ + overwriteRoutes?: boolean; + + /** + * as specified above + */ + response?: MockResponse | MockResponseFunction; + + /** + * integer, n, limiting the number of times the matcher can be used. + * If the route has already been called n times the route will be + * ignored and the call to fetch() will fall through to be handled by + * any other routes defined (which may eventually result in an error + * if nothing matches it). + */ + repeat?: number; + + /** + * integer, n, delays responding for the number of milliseconds + * specified. + */ + delay?: number; + + /** + * Convert objects into JSON before delivering as stub responses. Can + * be useful to set to false globally if e.g. dealing with a lot of + * array buffers. If true, will also add content-type: application/json + * header. + * @default true + */ + sendAsJson?: boolean; + + /** + * Automatically sets a content-length header on each response. + * @default true + */ + includeContentLength?: boolean; + + /** + * Match calls that only partially match a specified body json. + */ + matchPartialBody?: boolean; + } + + interface MockCall extends Array { + 0: string; + 1: RequestInit | undefined; + identifier: string; + isUnmatched: boolean | undefined; + request: Request | undefined; + response: Response | undefined; + } + + interface MockOptionsMethodGet extends MockOptions { + method?: 'GET'; + } + + interface MockOptionsMethodPost extends MockOptions { + method?: 'POST'; + } + + interface MockOptionsMethodPut extends MockOptions { + method?: 'PUT'; + } + + interface MockOptionsMethodDelete extends MockOptions { + method?: 'DELETE'; + } + + interface MockOptionsMethodPatch extends MockOptions { + method?: 'PATCH'; + } + + interface MockOptionsMethodHead extends MockOptions { + method?: 'HEAD'; + } + + interface FetchMockStatic { + MATCHED: true; + UNMATCHED: false; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Calls to .mock() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + mock(matcher: MockMatcher | MockOptions, response: MockResponse | MockResponseFunction, options?: MockOptions): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Calls to .mock() can be chained. + * @param options The route to mock + */ + mock(options: MockOptions): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Calls to .mock() can be chained. + * @param options The route to mock + */ + mock(): this; + + /** + * Returns a drop-in mock for fetch which can be passed to other mocking + * libraries. It implements the full fetch-mock api and maintains its + * own state independent of other instances, so tests can be run in + * parallel. + */ + sandbox(): FetchMockSandbox; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() limited to being + * called one time only. Calls to .once() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Optional additional properties defining the route to mock + */ + once(matcher: MockMatcher | MockOptions, response: MockResponse | MockResponseFunction, options?: MockOptions): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the GET + * method. Calls to .get() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + get(matcher: MockMatcher | MockOptionsMethodGet, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodGet): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the GET + * method and limited to being called one time only. Calls to .getOnce() + * can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + getOnce(matcher: MockMatcher | MockOptionsMethodGet, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodGet): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the POST + * method. Calls to .post() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + post(matcher: MockMatcher | MockOptionsMethodPost, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodPost): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the POST + * method and limited to being called one time only. Calls to .postOnce() + * can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + postOnce(matcher: MockMatcher | MockOptionsMethodPost, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodPost): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the PUT + * method. Calls to .put() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + put(matcher: MockMatcher | MockOptionsMethodPut, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodPut): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the PUT + * method and limited to being called one time only. Calls to .putOnce() + * can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + putOnce(matcher: MockMatcher | MockOptionsMethodPut, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodPut): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the + * DELETE method. Calls to .delete() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + delete(matcher: MockMatcher | MockOptionsMethodDelete, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodDelete): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the + * DELETE method and limited to being called one time only. Calls to + * .deleteOnce() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + deleteOnce(matcher: MockMatcher | MockOptionsMethodDelete, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodDelete): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the HEAD + * method. Calls to .head() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + head(matcher: MockMatcher | MockOptionsMethodHead, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodHead): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the HEAD + * method and limited to being called one time only. Calls to .headOnce() + * can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + headOnce(matcher: MockMatcher | MockOptionsMethodHead, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodHead): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the PATCH + * method. Calls to .patch() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + patch(matcher: MockMatcher | MockOptionsMethodPatch, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodPatch): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the PATCH + * method and limited to being called one time only. Calls to .patchOnce() + * can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + patchOnce(matcher: MockMatcher | MockOptionsMethodPatch, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodPatch): this; + + /** + * Chainable method that defines how to respond to calls to fetch that + * don't match any of the defined mocks. It accepts the same types of + * response as a normal call to .mock(matcher, response). It can also + * take an arbitrary function to completely customise behaviour of + * unmatched calls. If .catch() is called without any parameters then + * every unmatched call will receive a 200 response. + * @param [response] Configures the http response returned by the mock + */ + catch(response?: MockResponse | MockResponseFunction): this; + + /** + * Chainable method that records the call history of unmatched calls, + * but instead of responding with a stubbed response, the request is + * passed through to native fetch() and is allowed to communicate + * over the network. Similar to catch(). + */ + spy(response?: MockResponse | MockResponseFunction): this; + + /** + * Restores fetch() to its unstubbed state and clears all data recorded + * for its calls. reset() is an alias for restore(). + */ + restore(): this; + + /** + * Restores fetch() to its unstubbed state and clears all data recorded + * for its calls. reset() is an alias for restore(). + */ + reset(): this; + + /** + * Clears all data recorded for fetch()’s calls. It will not restore + * fetch to its default implementation. + */ + resetHistory(): this; + + /** + * Removes mocking behaviour without resetting call history. + */ + resetBehavior(): this; + + /** + * Returns a promise that resolves once all fetches handled by fetch-mock + * have resolved. + * @param [waitForBody] Wait for all body parsing methods(res.json(), + * res.text(), etc.) to resolve too. + */ + flush(waitForBody?: boolean): Promise; + + /** + * Returns an array of all calls to fetch matching the given filters. + * Each call is returned as a [url, options] array. If fetch was called + * using a Request instance, this will be available as a request + * property on this array. + * @param [filter] Allows filtering of calls to fetch based on various + * criteria + * @param [options] Either an object compatible with the mocking api or + * a string specifying a http method to filter by. This will be used to + * filter the list of calls further. + */ + calls(filter?: InspectionFilter, options?: InspectionOptions): MockCall[]; + + /** + * Returns a Boolean indicating whether any calls to fetch matched the + * given filter. + * @param [filter] Allows filtering of calls to fetch based on various + * criteria + * @param [options] Either an object compatible with the mocking api or + * a string specifying a http method to filter by. This will be used to + * filter the list of calls further. + */ + called(filter?: InspectionFilter, options?: InspectionOptions): boolean; + + /** + * Returns a Boolean indicating whether fetch was called the expected + * number of times (or has been called at least once if repeat is + * undefined for the route). + * @param [filter] Rule for matching calls to fetch. + */ + done(filter?: InspectionFilter): boolean; + + /** + * Returns the arguments for the last call to fetch matching the given + * filter. + * @param [filter] Allows filtering of calls to fetch based on various + * criteria + * @param [options] Either an object compatible with the mocking api or + * a string specifying a http method to filter by. This will be used to + * filter the list of calls further. + */ + lastCall( + filter?: InspectionFilter, + options?: InspectionOptions, + ): MockCall | undefined; + + /** + * Returns the url for the last call to fetch matching the given + * filter. If fetch was last called using a Request instance, the url + * will be extracted from this. + * @param [filter] Allows filtering of calls to fetch based on various + * criteria + * @param [options] Either an object compatible with the mocking api or + * a string specifying a http method to filter by. This will be used to + * filter the list of calls further. + */ + lastUrl( + filter?: InspectionFilter, + options?: InspectionOptions, + ): string | undefined; + + /** + * Returns the options for the call to fetch matching the given filter. + * If fetch was last called using a Request instance, a set of options + * inferred from the Request will be returned. + * @param [filter] Allows filtering of calls to fetch based on various + * criteria + * @param [options] Either an object compatible with the mocking api or + * a string specifying a http method to filter by. This will be used to + * filter the list of calls further. + */ + lastOptions( + filter?: InspectionFilter, + options?: InspectionOptions, + ): MockOptions | undefined; + + /** + * Returns the options for the call to fetch matching the given filter. + * This is an experimental feature, very difficult to implement well given + * fetch’s very private treatment of response bodies. + * When doing all the following: + - using node-fetch + - responding with a real network response (using spy() or fallbackToNetwork) + - using `fetchMock.LastResponse()` + - awaiting the body content + … the response will hang unless your source code also awaits the response body. + This is an unavoidable consequence of the nodejs implementation of streams. + * @param [filter] Allows filtering of calls to fetch based on various + * criteria + * @param [options] Either an object compatible with the mocking api or + * a string specifying a http method to filter by. This will be used to + * filter the list of calls further. + */ + lastResponse( + filter?: InspectionFilter, + options?: InspectionOptions, + ): Response | undefined; + + config: { + /** + * Convert objects into JSON before delivering as stub responses. + * Can be useful to set to false globally if e.g. dealing with a + * lot of array buffers. If true, will also add + * content-type: application/json header. + * @default true + */ + sendAsJson?: boolean; + + /** + * Automatically sets a content-length header on each response. + * @default true + */ + includeContentLength?: boolean; + + /** + * - true: Unhandled calls fall through to the network + * - false: Unhandled calls throw an error + * - 'always': All calls fall through to the network, effectively + * disabling fetch-mock. + * @default false + */ + fallbackToNetwork?: boolean | 'always'; + + /** + * Determines behaviour if a new route has the same name (or + * inferred name) as an existing one + * - undefined: An error will be throw when routes clash + * - true: Overwrites the existing route + * - false: Appends the new route to the list of routes + * @default undefined + */ + overwriteRoutes?: boolean; + + /** + * Print a warning if any call is caught by a fallback handler (set + * using the fallbackToNetwork option or catch()) + * @default true + */ + warnOnFallback?: boolean; + + /** + * Reference to the Promise constructor of a custom Promise + * implementation. + */ + Promise?: new (executor: ( + // Should be (value?: T | PromiseLike) => void + // But not sure if that's compatible with older typescript + resolve: (value?: any) => void, + reject: (value?: any) => void, + ) => void) => Promise; + + /** + * Reference to a custom fetch implementation. + */ + fetch?: ( + input?: string | Request, + init?: RequestInit, + ) => Promise; + + /** + * Reference to the Headers constructor of a custom fetch + * implementation. + */ + Headers?: new () => Headers; + + /** + * Reference to the Request constructor of a custom fetch + * implementation. + */ + Request?: new (input: string | Request, init?: RequestInit) => Request; + + /** + * Reference to the Response constructor of a custom fetch + * implementation. + */ + Response?: new () => Response; + }; + } + + interface FetchMockSandbox extends FetchMockStatic { + /** + * Also callable as fetch(). Use `typeof fetch` in your code to define + * a field that accepts both `fetch()` and a fetch-mock sandbox. + */ + (input?: string | Request , init?: RequestInit): Promise; + } +} + +declare var fetchMock: fetchMock.FetchMockStatic; +export = fetchMock; + +declare module 'fetch-mock/esm/client' { + const fetchMock: fetchMock.FetchMockStatic; + export default fetchMock; +} diff --git a/esm/client.js b/esm/client.js new file mode 100644 index 00000000..c4bdce7e --- /dev/null +++ b/esm/client.js @@ -0,0 +1,4825 @@ +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +var ms = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = ms; + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; +} + +var common = setup; + +var browser = createCommonjsModule(function (module, exports) { +/* eslint-env browser */ + +/** + * This is the web browser implementation of `debug()`. + */ + +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); + +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ +exports.log = console.debug || console.log || (() => {}); + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +module.exports = common(exports); + +const {formatters} = module.exports; + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; +}); +var browser_1 = browser.formatArgs; +var browser_2 = browser.save; +var browser_3 = browser.load; +var browser_4 = browser.useColors; +var browser_5 = browser.storage; +var browser_6 = browser.destroy; +var browser_7 = browser.colors; +var browser_8 = browser.log; + +let debugFunc; +let phase = 'default'; +let namespace = ''; +const newDebug = () => { + debugFunc = namespace + ? browser(`fetch-mock:${phase}:${namespace}`) + : browser(`fetch-mock:${phase}`); +}; + +const newDebugSandbox = (ns) => browser(`fetch-mock:${phase}:${ns}`); + +newDebug(); + +var debug_1 = { + debug: (...args) => { + debugFunc(...args); + }, + setDebugNamespace: (str) => { + namespace = str; + newDebug(); + }, + setDebugPhase: (str) => { + phase = str || 'default'; + newDebug(); + }, + getDebug: (namespace) => newDebugSandbox(namespace), +}; + +const { debug, setDebugPhase } = debug_1; +const FetchMock = {}; + +FetchMock.mock = function (...args) { + setDebugPhase('setup'); + if (args.length) { + this.addRoute(args); + } + + return this._mock(); +}; + +FetchMock.addRoute = function (uncompiledRoute) { + debug('Adding route', uncompiledRoute); + const route = this.compileRoute(uncompiledRoute); + const clashes = this.routes.filter(({ identifier, method }) => { + const isMatch = + typeof identifier === 'function' + ? identifier === route.identifier + : String(identifier) === String(route.identifier); + return isMatch && (!method || !route.method || method === route.method); + }); + + if (this.getOption('overwriteRoutes', route) === false || !clashes.length) { + this._uncompiledRoutes.push(uncompiledRoute); + return this.routes.push(route); + } + + if (this.getOption('overwriteRoutes', route) === true) { + clashes.forEach((clash) => { + const index = this.routes.indexOf(clash); + this._uncompiledRoutes.splice(index, 1, uncompiledRoute); + this.routes.splice(index, 1, route); + }); + return this.routes; + } + + if (clashes.length) { + throw new Error( + 'fetch-mock: Adding route with same name or matcher as existing route. See `overwriteRoutes` option.' + ); + } + + this._uncompiledRoutes.push(uncompiledRoute); + this.routes.push(route); +}; + +FetchMock._mock = function () { + if (!this.isSandbox) { + // Do this here rather than in the constructor to ensure it's scoped to the test + this.realFetch = this.realFetch || this.global.fetch; + this.global.fetch = this.fetchHandler; + } + setDebugPhase(); + return this; +}; + +FetchMock.catch = function (response) { + if (this.fallbackResponse) { + console.warn( + 'calling fetchMock.catch() twice - are you sure you want to overwrite the previous fallback response' + ); // eslint-disable-line + } + this.fallbackResponse = response || 'ok'; + return this._mock(); +}; + +FetchMock.spy = function (route) { + // even though ._mock() is called by .mock() and .catch() we still need to + // call it here otherwise .getNativeFetch() won't be able to use the reference + // to .realFetch that ._mock() sets up + this._mock(); + return route + ? this.mock(route, this.getNativeFetch()) + : this.catch(this.getNativeFetch()); +}; + +const defineShorthand = (methodName, underlyingMethod, shorthandOptions) => { + FetchMock[methodName] = function (matcher, response, options) { + return this[underlyingMethod]( + matcher, + response, + Object.assign(options || {}, shorthandOptions) + ); + }; +}; + +const defineGreedyShorthand = (methodName, underlyingMethod) => { + FetchMock[methodName] = function (response, options) { + return this[underlyingMethod]({}, response, options); + }; +}; + +defineShorthand('sticky', 'mock', { sticky: true }); +defineShorthand('once', 'mock', { repeat: 1 }); +defineGreedyShorthand('any', 'mock'); +defineGreedyShorthand('anyOnce', 'once'); + +['get', 'post', 'put', 'delete', 'head', 'patch'].forEach((method) => { + defineShorthand(method, 'mock', { method }); + defineShorthand(`${method}Once`, 'once', { method }); + defineGreedyShorthand(`${method}Any`, method); + defineGreedyShorthand(`${method}AnyOnce`, `${method}Once`); +}); + +const mochaAsyncHookWorkaround = (options) => { + // HACK workaround for this https://github.com/mochajs/mocha/issues/4280 + // Note that it doesn't matter that we call it _before_ carrying out all + // the things resetBehavior does as everything in there is synchronous + if (typeof options === 'function') { + console.warn(`Deprecated: Passing fetch-mock reset methods +directly in as handlers for before/after test runner hooks. +Wrap in an arrow function instead e.g. \`() => fetchMock.restore()\``); + options(); + } +}; + +const getRouteRemover = ({ sticky: removeStickyRoutes }) => (routes) => + removeStickyRoutes ? [] : routes.filter(({ sticky }) => sticky); + +FetchMock.resetBehavior = function (options = {}) { + mochaAsyncHookWorkaround(options); + const removeRoutes = getRouteRemover(options); + + this.routes = removeRoutes(this.routes); + this._uncompiledRoutes = removeRoutes(this._uncompiledRoutes); + + if (this.realFetch && !this.routes.length) { + this.global.fetch = this.realFetch; + this.realFetch = undefined; + } + + this.fallbackResponse = undefined; + return this; +}; + +FetchMock.resetHistory = function () { + this._calls = []; + this._holdingPromises = []; + this.routes.forEach((route) => route.reset && route.reset()); + return this; +}; + +FetchMock.restore = FetchMock.reset = function (options) { + this.resetBehavior(options); + this.resetHistory(); + return this; +}; + +var setUpAndTearDown = FetchMock; + +const { getDebug } = debug_1; +const responseConfigProps = [ + 'body', + 'headers', + 'throws', + 'status', + 'redirectUrl', +]; + +class ResponseBuilder { + constructor(options) { + this.debug = getDebug('ResponseBuilder()'); + this.debug('Response builder created with options', options); + Object.assign(this, options); + } + + exec() { + this.debug('building response'); + this.normalizeResponseConfig(); + this.constructFetchOpts(); + this.constructResponseBody(); + + const realResponse = new this.fetchMock.config.Response( + this.body, + this.options + ); + const proxyResponse = this.buildObservableResponse(realResponse); + return [realResponse, proxyResponse]; + } + + sendAsObject() { + if (responseConfigProps.some((prop) => this.responseConfig[prop])) { + if ( + Object.keys(this.responseConfig).every((key) => + responseConfigProps.includes(key) + ) + ) { + return false; + } else { + return true; + } + } else { + return true; + } + } + + normalizeResponseConfig() { + // If the response config looks like a status, start to generate a simple response + if (typeof this.responseConfig === 'number') { + this.debug('building response using status', this.responseConfig); + this.responseConfig = { + status: this.responseConfig, + }; + // If the response config is not an object, or is an object that doesn't use + // any reserved properties, assume it is meant to be the body of the response + } else if (typeof this.responseConfig === 'string' || this.sendAsObject()) { + this.debug('building text response from', this.responseConfig); + this.responseConfig = { + body: this.responseConfig, + }; + } + } + + validateStatus(status) { + if (!status) { + this.debug('No status provided. Defaulting to 200'); + return 200; + } + + if ( + (typeof status === 'number' && + parseInt(status, 10) !== status && + status >= 200) || + status < 600 + ) { + this.debug('Valid status provided', status); + return status; + } + + throw new TypeError(`fetch-mock: Invalid status ${status} passed on response object. +To respond with a JSON object that has status as a property assign the object to body +e.g. {"body": {"status: "registered"}}`); + } + + constructFetchOpts() { + this.options = this.responseConfig.options || {}; + this.options.url = this.responseConfig.redirectUrl || this.url; + this.options.status = this.validateStatus(this.responseConfig.status); + this.options.statusText = this.fetchMock.statusTextMap[ + String(this.options.status) + ]; + + // Set up response headers. The empty object is to cope with + // new Headers(undefined) throwing in Chrome + // https://code.google.com/p/chromium/issues/detail?id=335871 + this.options.headers = new this.fetchMock.config.Headers( + this.responseConfig.headers || {} + ); + } + + getOption(name) { + return this.fetchMock.getOption(name, this.route); + } + + convertToJson() { + // convert to json if we need to + if ( + this.getOption('sendAsJson') && + this.responseConfig.body != null && //eslint-disable-line + typeof this.body === 'object' + ) { + this.debug('Stringifying JSON response body'); + this.body = JSON.stringify(this.body); + if (!this.options.headers.has('Content-Type')) { + this.options.headers.set('Content-Type', 'application/json'); + } + } + } + + setContentLength() { + // add a Content-Length header if we need to + if ( + this.getOption('includeContentLength') && + typeof this.body === 'string' && + !this.options.headers.has('Content-Length') + ) { + this.debug('Setting content-length header:', this.body.length.toString()); + this.options.headers.set('Content-Length', this.body.length.toString()); + } + } + + constructResponseBody() { + // start to construct the body + this.body = this.responseConfig.body; + this.convertToJson(); + this.setContentLength(); + + // On the server we need to manually construct the readable stream for the + // Response object (on the client this done automatically) + if (this.Stream) { + this.debug('Creating response stream'); + const stream = new this.Stream.Readable(); + if (this.body != null) { //eslint-disable-line + stream.push(this.body, 'utf-8'); + } + stream.push(null); + this.body = stream; + } + this.body = this.body; + } + + buildObservableResponse(response) { + const fetchMock = this.fetchMock; + response._fmResults = {}; + // Using a proxy means we can set properties that may not be writable on + // the original Response. It also means we can track the resolution of + // promises returned by res.json(), res.text() etc + this.debug('Wrapping Response in ES proxy for observability'); + return new Proxy(response, { + get: (originalResponse, name) => { + if (this.responseConfig.redirectUrl) { + if (name === 'url') { + this.debug( + 'Retrieving redirect url', + this.responseConfig.redirectUrl + ); + return this.responseConfig.redirectUrl; + } + + if (name === 'redirected') { + this.debug('Retrieving redirected status', true); + return true; + } + } + + if (typeof originalResponse[name] === 'function') { + this.debug('Wrapping body promises in ES proxies for observability'); + return new Proxy(originalResponse[name], { + apply: (func, thisArg, args) => { + this.debug(`Calling res.${name}`); + const result = func.apply(response, args); + if (result.then) { + fetchMock._holdingPromises.push(result.catch(() => null)); + originalResponse._fmResults[name] = result; + } + return result; + }, + }); + } + + return originalResponse[name]; + }, + }); + } +} + +var responseBuilder = (options) => new ResponseBuilder(options).exec(); + +let URL; +// https://stackoverflow.com/a/19709846/308237 +// split, URL constructor does not support protocol-relative urls +const absoluteUrlRX = new RegExp('^[a-z]+://', 'i'); +const protocolRelativeUrlRX = new RegExp('^//', 'i'); + +const headersToArray = (headers) => { + // node-fetch 1 Headers + if (typeof headers.raw === 'function') { + return Object.entries(headers.raw()); + } else if (headers[Symbol.iterator]) { + return [...headers]; + } else { + return Object.entries(headers); + } +}; + +const zipObject = (entries) => + entries.reduce((obj, [key, val]) => Object.assign(obj, { [key]: val }), {}); + +const normalizeUrl = (url) => { + if ( + typeof url === 'function' || + url instanceof RegExp || + /^(begin|end|glob|express|path)\:/.test(url) + ) { + return url; + } + if (absoluteUrlRX.test(url)) { + const u = new URL(url); + return u.href; + } else if (protocolRelativeUrlRX.test(url)) { + const u = new URL(url, 'http://dummy'); + return u.href; + } else { + const u = new URL(url, 'http://dummy'); + return u.pathname + u.search; + } +}; + +const extractBody = async (request) => { + try { + // node-fetch + if ('body' in request) { + return request.body.toString(); + } + // fetch + return request.clone().text(); + } catch (err) {} +}; + +var requestUtils = { + setUrlImplementation: (it) => { + URL = it; + }, + normalizeRequest: (url, options, Request) => { + if (Request.prototype.isPrototypeOf(url)) { + const derivedOptions = { + method: url.method, + }; + + const body = extractBody(url); + + if (typeof body !== 'undefined') { + derivedOptions.body = body; + } + + const normalizedRequestObject = { + url: normalizeUrl(url.url), + options: Object.assign(derivedOptions, options), + request: url, + signal: (options && options.signal) || url.signal, + }; + + const headers = headersToArray(url.headers); + + if (headers.length) { + normalizedRequestObject.options.headers = zipObject(headers); + } + return normalizedRequestObject; + } else if ( + typeof url === 'string' || + // horrible URL object duck-typing + (typeof url === 'object' && 'href' in url) + ) { + return { + url: normalizeUrl(url), + options: options, + signal: options && options.signal, + }; + } else if (typeof url === 'object') { + throw new TypeError( + 'fetch-mock: Unrecognised Request object. Read the Config and Installation sections of the docs' + ); + } else { + throw new TypeError('fetch-mock: Invalid arguments passed to fetch'); + } + }, + normalizeUrl, + getPath: (url) => { + const u = absoluteUrlRX.test(url) + ? new URL(url) + : new URL(url, 'http://dummy'); + return u.pathname; + }, + + getQuery: (url) => { + const u = absoluteUrlRX.test(url) + ? new URL(url) + : new URL(url, 'http://dummy'); + return u.search ? u.search.substr(1) : ''; + }, + headers: { + normalize: (headers) => zipObject(headersToArray(headers)), + toLowerCase: (headers) => + Object.keys(headers).reduce((obj, k) => { + obj[k.toLowerCase()] = headers[k]; + return obj; + }, {}), + equal: (actualHeader, expectedHeader) => { + actualHeader = Array.isArray(actualHeader) + ? actualHeader + : [actualHeader]; + expectedHeader = Array.isArray(expectedHeader) + ? expectedHeader + : [expectedHeader]; + + if (actualHeader.length !== expectedHeader.length) { + return false; + } + + return actualHeader.every((val, i) => val === expectedHeader[i]); + }, + }, +}; + +const { debug: debug$1, setDebugPhase: setDebugPhase$1, getDebug: getDebug$1 } = debug_1; + + +const FetchMock$1 = {}; + +// see https://heycam.github.io/webidl/#aborterror for the standardised interface +// Note that this differs slightly from node-fetch +class AbortError extends Error { + constructor() { + super(...arguments); + this.name = 'AbortError'; + this.message = 'The operation was aborted.'; + + // Do not include this class in the stacktrace + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } +} + +// Patch native fetch to avoid "NotSupportedError:ReadableStream uploading is not supported" in Safari. +// See also https://github.com/wheresrhys/fetch-mock/issues/584 +// See also https://stackoverflow.com/a/50952018/1273406 +const patchNativeFetchForSafari = (nativeFetch) => { + // Try to patch fetch only on Safari + if ( + typeof navigator === 'undefined' || + !navigator.vendor || + navigator.vendor !== 'Apple Computer, Inc.' + ) { + return nativeFetch; + } + // It seems the code is working on Safari thus patch native fetch to avoid the error. + return async (request) => { + const { method } = request; + if (!['POST', 'PUT', 'PATCH'].includes(method)) { + // No patch is required in this case + return nativeFetch(request); + } + const body = await request.clone().text(); + const { + cache, + credentials, + headers, + integrity, + mode, + redirect, + referrer, + } = request; + const init = { + body, + cache, + credentials, + headers, + integrity, + mode, + redirect, + referrer, + method, + }; + return nativeFetch(request.url, init); + }; +}; + +const resolve = async ( + { response, responseIsFetch = false }, + url, + options, + request +) => { + const debug = getDebug$1('resolve()'); + debug('Recursively resolving function and promise responses'); + // We want to allow things like + // - function returning a Promise for a response + // - delaying (using a timeout Promise) a function's execution to generate + // a response + // Because of this we can't safely check for function before Promisey-ness, + // or vice versa. So to keep it DRY, and flexible, we keep trying until we + // have something that looks like neither Promise nor function + while (true) { + if (typeof response === 'function') { + debug(' Response is a function'); + // in the case of falling back to the network we need to make sure we're using + // the original Request instance, not our normalised url + options + if (responseIsFetch) { + if (request) { + debug(' -> Calling fetch with Request instance'); + return response(request); + } + debug(' -> Calling fetch with url and options'); + return response(url, options); + } else { + debug(' -> Calling response function'); + response = response(url, options, request); + } + } else if (typeof response.then === 'function') { + debug(' Response is a promise'); + debug(' -> Resolving promise'); + response = await response; + } else { + debug(' Response is not a function or a promise'); + debug(' -> Exiting response resolution recursion'); + return response; + } + } +}; + +FetchMock$1.needsAsyncBodyExtraction = function ({ request }) { + return request && this.routes.some(({ usesBody }) => usesBody); +}; + +FetchMock$1.fetchHandler = function (url, options) { + setDebugPhase$1('handle'); + const debug = getDebug$1('fetchHandler()'); + debug('fetch called with:', url, options); + + const normalizedRequest = requestUtils.normalizeRequest( + url, + options, + this.config.Request + ); + + debug('Request normalised'); + debug(' url', normalizedRequest.url); + debug(' options', normalizedRequest.options); + debug(' request', normalizedRequest.request); + debug(' signal', normalizedRequest.signal); + + if (this.needsAsyncBodyExtraction(normalizedRequest)) { + debug( + 'Need to wait for Body to be streamed before calling router: switching to async mode' + ); + return this._extractBodyThenHandle(normalizedRequest); + } + return this._fetchHandler(normalizedRequest); +}; + +FetchMock$1._extractBodyThenHandle = async function (normalizedRequest) { + normalizedRequest.options.body = await normalizedRequest.options.body; + return this._fetchHandler(normalizedRequest); +}; + +FetchMock$1._fetchHandler = function ({ url, options, request, signal }) { + const { route, callLog } = this.executeRouter(url, options, request); + + this.recordCall(callLog); + + // this is used to power the .flush() method + let done; + this._holdingPromises.push(new this.config.Promise((res) => (done = res))); + + // wrapped in this promise to make sure we respect custom Promise + // constructors defined by the user + return new this.config.Promise((res, rej) => { + if (signal) { + debug$1('signal exists - enabling fetch abort'); + const abort = () => { + debug$1('aborting fetch'); + // note that DOMException is not available in node.js; + // even node-fetch uses a custom error class: + // https://github.com/bitinn/node-fetch/blob/master/src/abort-error.js + rej( + typeof DOMException !== 'undefined' + ? new DOMException('The operation was aborted.', 'AbortError') + : new AbortError() + ); + done(); + }; + if (signal.aborted) { + debug$1('signal is already aborted - aborting the fetch'); + abort(); + } + signal.addEventListener('abort', abort); + } + + this.generateResponse({ route, url, options, request, callLog }) + .then(res, rej) + .then(done, done) + .then(() => { + setDebugPhase$1(); + }); + }); +}; + +FetchMock$1.fetchHandler.isMock = true; + +FetchMock$1.executeRouter = function (url, options, request) { + const debug = getDebug$1('executeRouter()'); + const callLog = { url, options, request, isUnmatched: true }; + debug(`Attempting to match request to a route`); + if (this.getOption('fallbackToNetwork') === 'always') { + debug( + ' Configured with fallbackToNetwork=always - passing through to fetch' + ); + return { + route: { response: this.getNativeFetch(), responseIsFetch: true }, + // BUG - this callLog never used to get sent. Discovered the bug + // but can't fix outside a major release as it will potentially + // cause too much disruption + // + // callLog, + }; + } + + const route = this.router(url, options, request); + + if (route) { + debug(' Matching route found'); + return { + route, + callLog: { + url, + options, + request, + identifier: route.identifier, + }, + }; + } + + if (this.getOption('warnOnFallback')) { + console.warn(`Unmatched ${(options && options.method) || 'GET'} to ${url}`); // eslint-disable-line + } + + if (this.fallbackResponse) { + debug(' No matching route found - using fallbackResponse'); + return { route: { response: this.fallbackResponse }, callLog }; + } + + if (!this.getOption('fallbackToNetwork')) { + throw new Error( + `fetch-mock: No fallback response defined for ${ + (options && options.method) || 'GET' + } to ${url}` + ); + } + + debug(' Configured to fallbackToNetwork - passing through to fetch'); + return { + route: { response: this.getNativeFetch(), responseIsFetch: true }, + callLog, + }; +}; + +FetchMock$1.generateResponse = async function ({ + route, + url, + options, + request, + callLog = {}, +}) { + const debug = getDebug$1('generateResponse()'); + const response = await resolve(route, url, options, request); + + // If the response says to throw an error, throw it + // Type checking is to deal with sinon spies having a throws property :-0 + if (response.throws && typeof response !== 'function') { + debug('response.throws is defined - throwing an error'); + throw response.throws; + } + + // If the response is a pre-made Response, respond with it + if (this.config.Response.prototype.isPrototypeOf(response)) { + debug('response is already a Response instance - returning it'); + callLog.response = response; + return response; + } + + // finally, if we need to convert config into a response, we do it + const [realResponse, finalResponse] = responseBuilder({ + url, + responseConfig: response, + fetchMock: this, + route, + }); + + callLog.response = realResponse; + + return finalResponse; +}; + +FetchMock$1.router = function (url, options, request) { + const route = this.routes.find((route, i) => { + debug$1(`Trying to match route ${i}`); + return route.matcher(url, options, request); + }); + + if (route) { + return route; + } +}; + +FetchMock$1.getNativeFetch = function () { + const func = this.realFetch || (this.isSandbox && this.config.fetch); + if (!func) { + throw new Error( + 'fetch-mock: Falling back to network only available on global fetch-mock, or by setting config.fetch on sandboxed fetch-mock' + ); + } + return patchNativeFetchForSafari(func); +}; + +FetchMock$1.recordCall = function (obj) { + debug$1('Recording fetch call', obj); + if (obj) { + this._calls.push(obj); + } +}; + +var fetchHandler = FetchMock$1; + +var globToRegexp = function (glob, opts) { + if (typeof glob !== 'string') { + throw new TypeError('Expected a string'); + } + + var str = String(glob); + + // The regexp we are building, as a string. + var reStr = ""; + + // Whether we are matching so called "extended" globs (like bash) and should + // support single character matching, matching ranges of characters, group + // matching, etc. + var extended = opts ? !!opts.extended : false; + + // When globstar is _false_ (default), '/foo/*' is translated a regexp like + // '^\/foo\/.*$' which will match any string beginning with '/foo/' + // When globstar is _true_, '/foo/*' is translated to regexp like + // '^\/foo\/[^/]*$' which will match any string beginning with '/foo/' BUT + // which does not have a '/' to the right of it. + // E.g. with '/foo/*' these will match: '/foo/bar', '/foo/bar.txt' but + // these will not '/foo/bar/baz', '/foo/bar/baz.txt' + // Lastely, when globstar is _true_, '/foo/**' is equivelant to '/foo/*' when + // globstar is _false_ + var globstar = opts ? !!opts.globstar : false; + + // If we are doing extended matching, this boolean is true when we are inside + // a group (eg {*.html,*.js}), and false otherwise. + var inGroup = false; + + // RegExp flags (eg "i" ) to pass in to RegExp constructor. + var flags = opts && typeof( opts.flags ) === "string" ? opts.flags : ""; + + var c; + for (var i = 0, len = str.length; i < len; i++) { + c = str[i]; + + switch (c) { + case "/": + case "$": + case "^": + case "+": + case ".": + case "(": + case ")": + case "=": + case "!": + case "|": + reStr += "\\" + c; + break; + + case "?": + if (extended) { + reStr += "."; + break; + } + + case "[": + case "]": + if (extended) { + reStr += c; + break; + } + + case "{": + if (extended) { + inGroup = true; + reStr += "("; + break; + } + + case "}": + if (extended) { + inGroup = false; + reStr += ")"; + break; + } + + case ",": + if (inGroup) { + reStr += "|"; + break; + } + reStr += "\\" + c; + break; + + case "*": + // Move over all consecutive "*"'s. + // Also store the previous and next characters + var prevChar = str[i - 1]; + var starCount = 1; + while(str[i + 1] === "*") { + starCount++; + i++; + } + var nextChar = str[i + 1]; + + if (!globstar) { + // globstar is disabled, so treat any number of "*" as one + reStr += ".*"; + } else { + // globstar is enabled, so determine if this is a globstar segment + var isGlobstar = starCount > 1 // multiple "*"'s + && (prevChar === "/" || prevChar === undefined) // from the start of the segment + && (nextChar === "/" || nextChar === undefined); // to the end of the segment + + if (isGlobstar) { + // it's a globstar, so match zero or more path segments + reStr += "((?:[^/]*(?:\/|$))*)"; + i++; // move over the "/" + } else { + // it's not a globstar, so only match one path segment + reStr += "([^/]*)"; + } + } + break; + + default: + reStr += c; + } + } + + // When regexp 'g' flag is specified don't + // constrain the regular expression with ^ & $ + if (!flags || !~flags.indexOf('g')) { + reStr = "^" + reStr + "$"; + } + + return new RegExp(reStr, flags); +}; + +/** + * Expose `pathToRegexp`. + */ +var pathToRegexp_1 = pathToRegexp; +var parse_1 = parse$1; +var compile_1 = compile; +var tokensToFunction_1 = tokensToFunction; +var tokensToRegExp_1 = tokensToRegExp; + +/** + * Default configs. + */ +var DEFAULT_DELIMITER = '/'; +var DEFAULT_DELIMITERS = './'; + +/** + * The main path matching regexp utility. + * + * @type {RegExp} + */ +var PATH_REGEXP = new RegExp([ + // Match escaped characters that would otherwise appear in future matches. + // This allows the user to escape special characters that won't transform. + '(\\\\.)', + // Match Express-style parameters and un-named parameters with a prefix + // and optional suffixes. Matches appear as: + // + // ":test(\\d+)?" => ["test", "\d+", undefined, "?"] + // "(\\d+)" => [undefined, undefined, "\d+", undefined] + '(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?' +].join('|'), 'g'); + +/** + * Parse a string for the raw tokens. + * + * @param {string} str + * @param {Object=} options + * @return {!Array} + */ +function parse$1 (str, options) { + var tokens = []; + var key = 0; + var index = 0; + var path = ''; + var defaultDelimiter = (options && options.delimiter) || DEFAULT_DELIMITER; + var delimiters = (options && options.delimiters) || DEFAULT_DELIMITERS; + var pathEscaped = false; + var res; + + while ((res = PATH_REGEXP.exec(str)) !== null) { + var m = res[0]; + var escaped = res[1]; + var offset = res.index; + path += str.slice(index, offset); + index = offset + m.length; + + // Ignore already escaped sequences. + if (escaped) { + path += escaped[1]; + pathEscaped = true; + continue + } + + var prev = ''; + var next = str[index]; + var name = res[2]; + var capture = res[3]; + var group = res[4]; + var modifier = res[5]; + + if (!pathEscaped && path.length) { + var k = path.length - 1; + + if (delimiters.indexOf(path[k]) > -1) { + prev = path[k]; + path = path.slice(0, k); + } + } + + // Push the current path onto the tokens. + if (path) { + tokens.push(path); + path = ''; + pathEscaped = false; + } + + var partial = prev !== '' && next !== undefined && next !== prev; + var repeat = modifier === '+' || modifier === '*'; + var optional = modifier === '?' || modifier === '*'; + var delimiter = prev || defaultDelimiter; + var pattern = capture || group; + + tokens.push({ + name: name || key++, + prefix: prev, + delimiter: delimiter, + optional: optional, + repeat: repeat, + partial: partial, + pattern: pattern ? escapeGroup(pattern) : '[^' + escapeString(delimiter) + ']+?' + }); + } + + // Push any remaining characters. + if (path || index < str.length) { + tokens.push(path + str.substr(index)); + } + + return tokens +} + +/** + * Compile a string to a template function for the path. + * + * @param {string} str + * @param {Object=} options + * @return {!function(Object=, Object=)} + */ +function compile (str, options) { + return tokensToFunction(parse$1(str, options)) +} + +/** + * Expose a method for transforming tokens into the path function. + */ +function tokensToFunction (tokens) { + // Compile all the tokens into regexps. + var matches = new Array(tokens.length); + + // Compile all the patterns before compilation. + for (var i = 0; i < tokens.length; i++) { + if (typeof tokens[i] === 'object') { + matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$'); + } + } + + return function (data, options) { + var path = ''; + var encode = (options && options.encode) || encodeURIComponent; + + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + + if (typeof token === 'string') { + path += token; + continue + } + + var value = data ? data[token.name] : undefined; + var segment; + + if (Array.isArray(value)) { + if (!token.repeat) { + throw new TypeError('Expected "' + token.name + '" to not repeat, but got array') + } + + if (value.length === 0) { + if (token.optional) continue + + throw new TypeError('Expected "' + token.name + '" to not be empty') + } + + for (var j = 0; j < value.length; j++) { + segment = encode(value[j], token); + + if (!matches[i].test(segment)) { + throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '"') + } + + path += (j === 0 ? token.prefix : token.delimiter) + segment; + } + + continue + } + + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + segment = encode(String(value), token); + + if (!matches[i].test(segment)) { + throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but got "' + segment + '"') + } + + path += token.prefix + segment; + continue + } + + if (token.optional) { + // Prepend partial segment prefixes. + if (token.partial) path += token.prefix; + + continue + } + + throw new TypeError('Expected "' + token.name + '" to be ' + (token.repeat ? 'an array' : 'a string')) + } + + return path + } +} + +/** + * Escape a regular expression string. + * + * @param {string} str + * @return {string} + */ +function escapeString (str) { + return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1') +} + +/** + * Escape the capturing group by escaping special characters and meaning. + * + * @param {string} group + * @return {string} + */ +function escapeGroup (group) { + return group.replace(/([=!:$/()])/g, '\\$1') +} + +/** + * Get the flags for a regexp from the options. + * + * @param {Object} options + * @return {string} + */ +function flags (options) { + return options && options.sensitive ? '' : 'i' +} + +/** + * Pull out keys from a regexp. + * + * @param {!RegExp} path + * @param {Array=} keys + * @return {!RegExp} + */ +function regexpToRegexp (path, keys) { + if (!keys) return path + + // Use a negative lookahead to match only capturing groups. + var groups = path.source.match(/\((?!\?)/g); + + if (groups) { + for (var i = 0; i < groups.length; i++) { + keys.push({ + name: i, + prefix: null, + delimiter: null, + optional: false, + repeat: false, + partial: false, + pattern: null + }); + } + } + + return path +} + +/** + * Transform an array into a regexp. + * + * @param {!Array} path + * @param {Array=} keys + * @param {Object=} options + * @return {!RegExp} + */ +function arrayToRegexp (path, keys, options) { + var parts = []; + + for (var i = 0; i < path.length; i++) { + parts.push(pathToRegexp(path[i], keys, options).source); + } + + return new RegExp('(?:' + parts.join('|') + ')', flags(options)) +} + +/** + * Create a path regexp from string input. + * + * @param {string} path + * @param {Array=} keys + * @param {Object=} options + * @return {!RegExp} + */ +function stringToRegexp (path, keys, options) { + return tokensToRegExp(parse$1(path, options), keys, options) +} + +/** + * Expose a function for taking tokens and returning a RegExp. + * + * @param {!Array} tokens + * @param {Array=} keys + * @param {Object=} options + * @return {!RegExp} + */ +function tokensToRegExp (tokens, keys, options) { + options = options || {}; + + var strict = options.strict; + var start = options.start !== false; + var end = options.end !== false; + var delimiter = escapeString(options.delimiter || DEFAULT_DELIMITER); + var delimiters = options.delimiters || DEFAULT_DELIMITERS; + var endsWith = [].concat(options.endsWith || []).map(escapeString).concat('$').join('|'); + var route = start ? '^' : ''; + var isEndDelimited = tokens.length === 0; + + // Iterate over the tokens and create our regexp string. + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + + if (typeof token === 'string') { + route += escapeString(token); + isEndDelimited = i === tokens.length - 1 && delimiters.indexOf(token[token.length - 1]) > -1; + } else { + var capture = token.repeat + ? '(?:' + token.pattern + ')(?:' + escapeString(token.delimiter) + '(?:' + token.pattern + '))*' + : token.pattern; + + if (keys) keys.push(token); + + if (token.optional) { + if (token.partial) { + route += escapeString(token.prefix) + '(' + capture + ')?'; + } else { + route += '(?:' + escapeString(token.prefix) + '(' + capture + '))?'; + } + } else { + route += escapeString(token.prefix) + '(' + capture + ')'; + } + } + } + + if (end) { + if (!strict) route += '(?:' + delimiter + ')?'; + + route += endsWith === '$' ? '$' : '(?=' + endsWith + ')'; + } else { + if (!strict) route += '(?:' + delimiter + '(?=' + endsWith + '))?'; + if (!isEndDelimited) route += '(?=' + delimiter + '|' + endsWith + ')'; + } + + return new RegExp(route, flags(options)) +} + +/** + * Normalize the given path string, returning a regular expression. + * + * An empty array can be passed in for the keys, which will hold the + * placeholder key descriptions. For example, using `/user/:id`, `keys` will + * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`. + * + * @param {(string|RegExp|Array)} path + * @param {Array=} keys + * @param {Object=} options + * @return {!RegExp} + */ +function pathToRegexp (path, keys, options) { + if (path instanceof RegExp) { + return regexpToRegexp(path, keys) + } + + if (Array.isArray(path)) { + return arrayToRegexp(/** @type {!Array} */ (path), keys, options) + } + + return stringToRegexp(/** @type {string} */ (path), keys, options) +} +pathToRegexp_1.parse = parse_1; +pathToRegexp_1.compile = compile_1; +pathToRegexp_1.tokensToFunction = tokensToFunction_1; +pathToRegexp_1.tokensToRegExp = tokensToRegExp_1; + +// Copyright Joyent, Inc. and other Node contributors. + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +var decode = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (Array.isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +// Copyright Joyent, Inc. and other Node contributors. + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +var encode = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return Object.keys(obj).map(function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (Array.isArray(obj[k])) { + return obj[k].map(function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var querystring = createCommonjsModule(function (module, exports) { + +exports.decode = exports.parse = decode; +exports.encode = exports.stringify = encode; +}); +var querystring_1 = querystring.decode; +var querystring_2 = querystring.parse; +var querystring_3 = querystring.encode; +var querystring_4 = querystring.stringify; + +var isSubset_1 = createCommonjsModule(function (module, exports) { + +Object.defineProperty(exports, '__esModule', { + value: true +}); +/** + * Check if an object is contained within another object. + * + * Returns `true` if: + * - all enumerable keys of *subset* are also enumerable in *superset*, and + * - every value assigned to an enumerable key of *subset* strictly equals + * the value assigned to the same key of *superset* – or is a subset of it. + * + * @param {Object} superset + * @param {Object} subset + * + * @returns {Boolean} + * + * @module is-subset + * @function default + * @alias isSubset + */ +var isSubset = (function (_isSubset) { + function isSubset(_x, _x2) { + return _isSubset.apply(this, arguments); + } + + isSubset.toString = function () { + return _isSubset.toString(); + }; + + return isSubset; +})(function (superset, subset) { + if (typeof superset !== 'object' || superset === null || (typeof subset !== 'object' || subset === null)) return false; + + return Object.keys(subset).every(function (key) { + if (!superset.propertyIsEnumerable(key)) return false; + + var subsetItem = subset[key]; + var supersetItem = superset[key]; + if (typeof subsetItem === 'object' && subsetItem !== null ? !isSubset(supersetItem, subsetItem) : supersetItem !== subsetItem) return false; + + return true; + }); +}); + +exports['default'] = isSubset; +module.exports = exports['default']; +}); + +unwrapExports(isSubset_1); + +var lodash_isequal = createCommonjsModule(function (module, exports) { +/** + * Lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright JS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + nullTag = '[object Null]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + undefinedTag = '[object Undefined]', + weakMapTag = '[object WeakMap]'; + +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** Used to identify `toStringTag` values of typed arrays. */ +var typedArrayTags = {}; +typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = +typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = +typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = +typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = +typedArrayTags[uint32Tag] = true; +typedArrayTags[argsTag] = typedArrayTags[arrayTag] = +typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = +typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = +typedArrayTags[errorTag] = typedArrayTags[funcTag] = +typedArrayTags[mapTag] = typedArrayTags[numberTag] = +typedArrayTags[objectTag] = typedArrayTags[regexpTag] = +typedArrayTags[setTag] = typedArrayTags[stringTag] = +typedArrayTags[weakMapTag] = false; + +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); + +/** Detect free variable `exports`. */ +var freeExports = exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; + +/** Detect free variable `process` from Node.js. */ +var freeProcess = moduleExports && freeGlobal.process; + +/** Used to access faster Node.js helpers. */ +var nodeUtil = (function() { + try { + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} +}()); + +/* Node.js helper references. */ +var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + +/** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ +function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; +} + +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; +} + +/** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ +function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; +} + +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +/** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ +function baseUnary(func) { + return function(value) { + return func(value); + }; +} + +/** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function cacheHas(cache, key) { + return cache.has(key); +} + +/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function getValue(object, key) { + return object == null ? undefined : object[key]; +} + +/** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ +function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; +} + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +/** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ +function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; +} + +/** Used for built-in method references. */ +var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + +/** Used to detect overreaching core-js shims. */ +var coreJsData = root['__core-js_shared__']; + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** Used to detect methods masquerading as native. */ +var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; +}()); + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; + +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); + +/** Built-in value references. */ +var Buffer = moduleExports ? root.Buffer : undefined, + Symbol = root.Symbol, + Uint8Array = root.Uint8Array, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + symToStringTag = Symbol ? Symbol.toStringTag : undefined; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeKeys = overArg(Object.keys, Object); + +/* Built-in method references that are verified to be native. */ +var DataView = getNative(root, 'DataView'), + Map = getNative(root, 'Map'), + Promise = getNative(root, 'Promise'), + Set = getNative(root, 'Set'), + WeakMap = getNative(root, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); + +/** Used to detect maps, sets, and weakmaps. */ +var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; + +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ +function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; +} + +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; +} + +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; +} + +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); +} + +/** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ +function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; +} + +// Add methods to `Hash`. +Hash.prototype.clear = hashClear; +Hash.prototype['delete'] = hashDelete; +Hash.prototype.get = hashGet; +Hash.prototype.has = hashHas; +Hash.prototype.set = hashSet; + +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; + this.size = 0; +} + +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; +} + +/** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; +} + +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; +} + +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ +function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; +} + +// Add methods to `ListCache`. +ListCache.prototype.clear = listCacheClear; +ListCache.prototype['delete'] = listCacheDelete; +ListCache.prototype.get = listCacheGet; +ListCache.prototype.has = listCacheHas; +ListCache.prototype.set = listCacheSet; + +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ +function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; +} + +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; +} + +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function mapCacheGet(key) { + return getMapData(this, key).get(key); +} + +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function mapCacheHas(key) { + return getMapData(this, key).has(key); +} + +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ +function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; +} + +// Add methods to `MapCache`. +MapCache.prototype.clear = mapCacheClear; +MapCache.prototype['delete'] = mapCacheDelete; +MapCache.prototype.get = mapCacheGet; +MapCache.prototype.has = mapCacheHas; +MapCache.prototype.set = mapCacheSet; + +/** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ +function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } +} + +/** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ +function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; +} + +/** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ +function setCacheHas(value) { + return this.__data__.has(value); +} + +// Add methods to `SetCache`. +SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; +SetCache.prototype.has = setCacheHas; + +/** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; +} + +/** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ +function stackClear() { + this.__data__ = new ListCache; + this.size = 0; +} + +/** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; +} + +/** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function stackGet(key) { + return this.__data__.get(key); +} + +/** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function stackHas(key) { + return this.__data__.has(key); +} + +/** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ +function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; +} + +// Add methods to `Stack`. +Stack.prototype.clear = stackClear; +Stack.prototype['delete'] = stackDelete; +Stack.prototype.get = stackGet; +Stack.prototype.has = stackHas; +Stack.prototype.set = stackSet; + +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; +} + +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; +} + +/** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ +function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); +} + +/** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); +} + +/** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ +function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; +} + +/** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ +function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); +} + +/** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other); + + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); +} + +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ +function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); +} + +/** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ +function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; +} + +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; +} + +/** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ +function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; +} + +/** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; +} + +/** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; +} + +/** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ +function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); +} + +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ +function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; +} + +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; +} + +/** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ +function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; +} + +/** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ +var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); +}; + +/** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +var getTag = baseGetTag; + +// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. +if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; +} + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); +} + +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); +} + +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); +} + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; +} + +/** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ +function objectToString(value) { + return nativeObjectToString.call(value); +} + +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; +} + +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); +}; + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +/** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ +var isBuffer = nativeIsBuffer || stubFalse; + +/** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ +function isEqual(value, other) { + return baseIsEqual(value, other); +} + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; +} + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return value != null && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ +var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} + +/** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ +function stubArray() { + return []; +} + +/** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ +function stubFalse() { + return false; +} + +module.exports = isEqual; +}); + +const { debug: debug$2 } = debug_1; + + + + +const { + headers: headerUtils, + getPath, + getQuery, + normalizeUrl: normalizeUrl$1, +} = requestUtils; + + +const debuggableUrlFunc = (func) => (url) => { + debug$2('Actual url:', url); + return func(url); +}; + +const stringMatchers = { + begin: (targetString) => + debuggableUrlFunc((url) => url.indexOf(targetString) === 0), + end: (targetString) => + debuggableUrlFunc( + (url) => url.substr(-targetString.length) === targetString + ), + glob: (targetString) => { + const urlRX = globToRegexp(targetString); + return debuggableUrlFunc((url) => urlRX.test(url)); + }, + express: (targetString) => { + const urlRX = pathToRegexp_1(targetString); + return debuggableUrlFunc((url) => urlRX.test(getPath(url))); + }, + path: (targetString) => + debuggableUrlFunc((url) => getPath(url) === targetString), +}; + +const getHeaderMatcher = ({ headers: expectedHeaders }) => { + debug$2('Generating header matcher'); + if (!expectedHeaders) { + debug$2(' No header expectations defined - skipping'); + return; + } + const expectation = headerUtils.toLowerCase(expectedHeaders); + debug$2(' Expected headers:', expectation); + return (url, { headers = {} }) => { + debug$2('Attempting to match headers'); + const lowerCaseHeaders = headerUtils.toLowerCase( + headerUtils.normalize(headers) + ); + debug$2(' Expected headers:', expectation); + debug$2(' Actual headers:', lowerCaseHeaders); + return Object.keys(expectation).every((headerName) => + headerUtils.equal(lowerCaseHeaders[headerName], expectation[headerName]) + ); + }; +}; + +const getMethodMatcher = ({ method: expectedMethod }) => { + debug$2('Generating method matcher'); + if (!expectedMethod) { + debug$2(' No method expectations defined - skipping'); + return; + } + debug$2(' Expected method:', expectedMethod); + return (url, { method }) => { + debug$2('Attempting to match method'); + const actualMethod = method ? method.toLowerCase() : 'get'; + debug$2(' Expected method:', expectedMethod); + debug$2(' Actual method:', actualMethod); + return expectedMethod === actualMethod; + }; +}; + +const getQueryStringMatcher = ({ query: passedQuery }) => { + debug$2('Generating query parameters matcher'); + if (!passedQuery) { + debug$2(' No query parameters expectations defined - skipping'); + return; + } + const expectedQuery = querystring.parse(querystring.stringify(passedQuery)); + debug$2(' Expected query parameters:', passedQuery); + const keys = Object.keys(expectedQuery); + return (url) => { + debug$2('Attempting to match query parameters'); + const query = querystring.parse(getQuery(url)); + debug$2(' Expected query parameters:', expectedQuery); + debug$2(' Actual query parameters:', query); + return keys.every((key) => { + if (Array.isArray(query[key])) { + if (!Array.isArray(expectedQuery[key])) { + return false; + } else { + return lodash_isequal(query[key].sort(), expectedQuery[key].sort()); + } + } + return query[key] === expectedQuery[key]; + }); + }; +}; + +const getParamsMatcher = ({ params: expectedParams, url: matcherUrl }) => { + debug$2('Generating path parameters matcher'); + if (!expectedParams) { + debug$2(' No path parameters expectations defined - skipping'); + return; + } + if (!/express:/.test(matcherUrl)) { + throw new Error( + 'fetch-mock: matching on params is only possible when using an express: matcher' + ); + } + debug$2(' Expected path parameters:', expectedParams); + const expectedKeys = Object.keys(expectedParams); + const keys = []; + const re = pathToRegexp_1(matcherUrl.replace(/^express:/, ''), keys); + return (url) => { + debug$2('Attempting to match path parameters'); + const vals = re.exec(getPath(url)) || []; + vals.shift(); + const params = keys.reduce( + (map, { name }, i) => + vals[i] ? Object.assign(map, { [name]: vals[i] }) : map, + {} + ); + debug$2(' Expected path parameters:', expectedParams); + debug$2(' Actual path parameters:', params); + return expectedKeys.every((key) => params[key] === expectedParams[key]); + }; +}; + +const getBodyMatcher = (route, fetchMock) => { + const matchPartialBody = fetchMock.getOption('matchPartialBody', route); + const { body: expectedBody } = route; + + debug$2('Generating body matcher'); + return (url, { body, method = 'get' }) => { + debug$2('Attempting to match body'); + if (method.toLowerCase() === 'get') { + debug$2(' GET request - skip matching body'); + // GET requests don’t send a body so the body matcher should be ignored for them + return true; + } + + let sentBody = body; + + try { + debug$2(' Parsing request body as JSON'); + sentBody = JSON.parse(body); + } catch (err) { + debug$2(' Failed to parse request body as JSON', err); + } + debug$2('Expected body:', expectedBody); + debug$2('Actual body:', sentBody); + if (matchPartialBody) { + debug$2('matchPartialBody is true - checking for partial match only'); + } + + return ( + sentBody && + (matchPartialBody + ? isSubset_1(sentBody, expectedBody) + : lodash_isequal(sentBody, expectedBody)) + ); + }; +}; + +const getFullUrlMatcher = (route, matcherUrl, query) => { + // if none of the special syntaxes apply, it's just a simple string match + // but we have to be careful to normalize the url we check and the name + // of the route to allow for e.g. http://it.at.there being indistinguishable + // from http://it.at.there/ once we start generating Request/Url objects + debug$2(' Matching using full url', matcherUrl); + const expectedUrl = normalizeUrl$1(matcherUrl); + debug$2(' Normalised url to:', matcherUrl); + if (route.identifier === matcherUrl) { + debug$2(' Updating route identifier to match normalized url:', matcherUrl); + route.identifier = expectedUrl; + } + + return (matcherUrl) => { + debug$2('Expected url:', expectedUrl); + debug$2('Actual url:', matcherUrl); + if (query && expectedUrl.indexOf('?')) { + debug$2('Ignoring query string when matching url'); + return matcherUrl.indexOf(expectedUrl) === 0; + } + return normalizeUrl$1(matcherUrl) === expectedUrl; + }; +}; + +const getFunctionMatcher = ({ functionMatcher }) => { + debug$2('Detected user defined function matcher', functionMatcher); + return (...args) => { + debug$2('Calling function matcher with arguments', args); + return functionMatcher(...args); + }; +}; + +const getUrlMatcher = (route) => { + debug$2('Generating url matcher'); + const { url: matcherUrl, query } = route; + + if (matcherUrl === '*') { + debug$2(' Using universal * rule to match any url'); + return () => true; + } + + if (matcherUrl instanceof RegExp) { + debug$2(' Using regular expression to match url:', matcherUrl); + return (url) => matcherUrl.test(url); + } + + if (matcherUrl.href) { + debug$2(` Using URL object to match url`, matcherUrl); + return getFullUrlMatcher(route, matcherUrl.href, query); + } + + for (const shorthand in stringMatchers) { + if (matcherUrl.indexOf(shorthand + ':') === 0) { + debug$2(` Using ${shorthand}: pattern to match url`, matcherUrl); + const urlFragment = matcherUrl.replace(new RegExp(`^${shorthand}:`), ''); + return stringMatchers[shorthand](urlFragment); + } + } + + return getFullUrlMatcher(route, matcherUrl, query); +}; + +var matchers = [ + { name: 'query', matcher: getQueryStringMatcher }, + { name: 'method', matcher: getMethodMatcher }, + { name: 'headers', matcher: getHeaderMatcher }, + { name: 'params', matcher: getParamsMatcher }, + { name: 'body', matcher: getBodyMatcher, usesBody: true }, + { name: 'functionMatcher', matcher: getFunctionMatcher }, + { name: 'url', matcher: getUrlMatcher }, +]; + +const { debug: debug$3, setDebugNamespace, getDebug: getDebug$2 } = debug_1; + +const isUrlMatcher = (matcher) => + matcher instanceof RegExp || + typeof matcher === 'string' || + (typeof matcher === 'object' && 'href' in matcher); + +const isFunctionMatcher = (matcher) => typeof matcher === 'function'; + +class Route { + constructor(args, fetchMock) { + this.fetchMock = fetchMock; + const debug = getDebug$2('compileRoute()'); + debug('Compiling route'); + this.init(args); + this.sanitize(); + this.validate(); + this.generateMatcher(); + this.limit(); + this.delayResponse(); + } + + validate() { + if (!('response' in this)) { + throw new Error('fetch-mock: Each route must define a response'); + } + + if (!Route.registeredMatchers.some(({ name }) => name in this)) { + throw new Error( + "fetch-mock: Each route must specify some criteria for matching calls to fetch. To match all calls use '*'" + ); + } + } + + init(args) { + const [matcher, response, options = {}] = args; + + const routeConfig = {}; + + if (isUrlMatcher(matcher) || isFunctionMatcher(matcher)) { + routeConfig.matcher = matcher; + } else { + Object.assign(routeConfig, matcher); + } + + if (typeof response !== 'undefined') { + routeConfig.response = response; + } + + Object.assign(routeConfig, options); + Object.assign(this, routeConfig); + } + + sanitize() { + const debug = getDebug$2('sanitize()'); + debug('Sanitizing route properties'); + + if (this.method) { + debug(`Converting method ${this.method} to lower case`); + this.method = this.method.toLowerCase(); + } + if (isUrlMatcher(this.matcher)) { + debug('Mock uses a url matcher', this.matcher); + this.url = this.matcher; + delete this.matcher; + } + + this.functionMatcher = this.matcher || this.functionMatcher; + + debug('Setting route.identifier...'); + debug(` route.name is ${this.name}`); + debug(` route.url is ${this.url}`); + debug(` route.functionMatcher is ${this.functionMatcher}`); + this.identifier = this.name || this.url || this.functionMatcher; + debug(` -> route.identifier set to ${this.identifier}`); + } + + generateMatcher() { + setDebugNamespace('generateMatcher()'); + debug$3('Compiling matcher for route'); + + const activeMatchers = Route.registeredMatchers + .map( + ({ name, matcher, usesBody }) => + this[name] && { matcher: matcher(this, this.fetchMock), usesBody } + ) + .filter((matcher) => Boolean(matcher)); + + this.usesBody = activeMatchers.some(({ usesBody }) => usesBody); + + debug$3('Compiled matcher for route'); + setDebugNamespace(); + this.matcher = (url, options = {}, request) => + activeMatchers.every(({ matcher }) => matcher(url, options, request)); + } + + limit() { + const debug = getDebug$2('limit()'); + debug('Limiting number of requests to handle by route'); + if (!this.repeat) { + debug( + ' No `repeat` value set on route. Will match any number of requests' + ); + return; + } + + debug(` Route set to repeat ${this.repeat} times`); + const matcher = this.matcher; + let timesLeft = this.repeat; + this.matcher = (url, options) => { + const match = timesLeft && matcher(url, options); + if (match) { + timesLeft--; + return true; + } + }; + this.reset = () => (timesLeft = this.repeat); + } + + delayResponse() { + const debug = getDebug$2('delayResponse()'); + debug(`Applying response delay settings`); + if (this.delay) { + debug(` Wrapping response in delay of ${this.delay} miliseconds`); + const response = this.response; + this.response = () => { + debug(`Delaying response by ${this.delay} miliseconds`); + return new Promise((res) => + setTimeout(() => res(response), this.delay) + ); + }; + } else { + debug( + ` No delay set on route. Will respond 'immediately' (but asynchronously)` + ); + } + } + + static addMatcher(matcher) { + Route.registeredMatchers.push(matcher); + } +} + +Route.registeredMatchers = []; + +matchers.forEach(Route.addMatcher); + +var Route_1 = Route; + +const { setDebugPhase: setDebugPhase$2, setDebugNamespace: setDebugNamespace$1, debug: debug$4 } = debug_1; +const { normalizeUrl: normalizeUrl$2 } = requestUtils; + +const FetchMock$2 = {}; +const isName = (nameOrMatcher) => + typeof nameOrMatcher === 'string' && /^[\da-zA-Z\-]+$/.test(nameOrMatcher); + +const filterCallsWithMatcher = function (matcher, options = {}, calls) { + ({ matcher } = new Route_1( + [Object.assign({ matcher, response: 'ok' }, options)], + this + )); + return calls.filter(({ url, options }) => + matcher(normalizeUrl$2(url), options) + ); +}; + +const formatDebug = (func) => { + return function (...args) { + setDebugPhase$2('inspect'); + const result = func.call(this, ...args); + setDebugPhase$2(); + return result; + }; +}; + +const callObjToArray = (obj) => { + if (!obj) { + return undefined; + } + const { url, options, request, identifier, isUnmatched, response } = obj; + const arr = [url, options]; + arr.request = request; + arr.identifier = identifier; + arr.isUnmatched = isUnmatched; + arr.response = response; + return arr; +}; + +FetchMock$2.filterCalls = function (nameOrMatcher, options) { + debug$4('Filtering fetch calls'); + let calls = this._calls; + let matcher = '*'; + + if ([true, 'matched'].includes(nameOrMatcher)) { + debug$4(`Filter provided is ${nameOrMatcher}. Returning matched calls only`); + calls = calls.filter(({ isUnmatched }) => !isUnmatched); + } else if ([false, 'unmatched'].includes(nameOrMatcher)) { + debug$4( + `Filter provided is ${nameOrMatcher}. Returning unmatched calls only` + ); + calls = calls.filter(({ isUnmatched }) => isUnmatched); + } else if (typeof nameOrMatcher === 'undefined') { + debug$4(`Filter provided is undefined. Returning all calls`); + calls = calls; + } else if (isName(nameOrMatcher)) { + debug$4( + `Filter provided, looks like the name of a named route. Returning only calls handled by that route` + ); + calls = calls.filter(({ identifier }) => identifier === nameOrMatcher); + } else { + matcher = nameOrMatcher === '*' ? '*' : normalizeUrl$2(nameOrMatcher); + if (this.routes.some(({ identifier }) => identifier === matcher)) { + debug$4( + `Filter provided, ${nameOrMatcher}, identifies a route. Returning only calls handled by that route` + ); + calls = calls.filter((call) => call.identifier === matcher); + } + } + + if ((options || matcher !== '*') && calls.length) { + if (typeof options === 'string') { + options = { method: options }; + } + debug$4( + 'Compiling filter and options to route in order to filter all calls', + nameOrMatcher + ); + calls = filterCallsWithMatcher.call(this, matcher, options, calls); + } + debug$4(`Retrieved ${calls.length} calls`); + return calls.map(callObjToArray); +}; + +FetchMock$2.calls = formatDebug(function (nameOrMatcher, options) { + debug$4('retrieving matching calls'); + return this.filterCalls(nameOrMatcher, options); +}); + +FetchMock$2.lastCall = formatDebug(function (nameOrMatcher, options) { + debug$4('retrieving last matching call'); + return [...this.filterCalls(nameOrMatcher, options)].pop(); +}); + +FetchMock$2.lastUrl = formatDebug(function (nameOrMatcher, options) { + debug$4('retrieving url of last matching call'); + return (this.lastCall(nameOrMatcher, options) || [])[0]; +}); + +FetchMock$2.lastOptions = formatDebug(function (nameOrMatcher, options) { + debug$4('retrieving options of last matching call'); + return (this.lastCall(nameOrMatcher, options) || [])[1]; +}); + +FetchMock$2.lastResponse = formatDebug(function (nameOrMatcher, options) { + debug$4('retrieving respose of last matching call'); + console.warn(`When doing all the following: +- using node-fetch +- responding with a real network response (using spy() or fallbackToNetwork) +- using \`fetchMock.LastResponse()\` +- awaiting the body content +... the response will hang unless your source code also awaits the response body. +This is an unavoidable consequence of the nodejs implementation of streams. +`); + const response = (this.lastCall(nameOrMatcher, options) || []).response; + try { + const clonedResponse = response.clone(); + return clonedResponse; + } catch (err) { + Object.entries(response._fmResults).forEach(([name, result]) => { + response[name] = () => result; + }); + return response; + } +}); + +FetchMock$2.called = formatDebug(function (nameOrMatcher, options) { + debug$4('checking if matching call was made'); + return Boolean(this.filterCalls(nameOrMatcher, options).length); +}); + +FetchMock$2.flush = formatDebug(async function (waitForResponseMethods) { + setDebugNamespace$1('flush'); + debug$4( + `flushing all fetch calls. ${ + waitForResponseMethods ? '' : 'Not ' + }waiting for response bodies to complete download` + ); + + const queuedPromises = this._holdingPromises; + this._holdingPromises = []; + debug$4(`${queuedPromises.length} fetch calls to be awaited`); + + await Promise.all(queuedPromises); + debug$4(`All fetch calls have completed`); + if (waitForResponseMethods && this._holdingPromises.length) { + debug$4(`Awaiting all fetch bodies to download`); + await this.flush(waitForResponseMethods); + debug$4(`All fetch bodies have completed downloading`); + } + setDebugNamespace$1(); +}); + +FetchMock$2.done = formatDebug(function (nameOrMatcher) { + setDebugPhase$2('inspect'); + setDebugNamespace$1('done'); + debug$4('Checking to see if expected calls have been made'); + let routesToCheck; + + if (nameOrMatcher && typeof nameOrMatcher !== 'boolean') { + debug$4( + 'Checking to see if expected calls have been made for single route:', + nameOrMatcher + ); + routesToCheck = [{ identifier: nameOrMatcher }]; + } else { + debug$4('Checking to see if expected calls have been made for all routes'); + routesToCheck = this.routes; + } + + // Can't use array.every because would exit after first failure, which would + // break the logging + const result = routesToCheck + .map(({ identifier }) => { + if (!this.called(identifier)) { + debug$4('No calls made for route:', identifier); + console.warn(`Warning: ${identifier} not called`); // eslint-disable-line + return false; + } + + const expectedTimes = ( + this.routes.find((r) => r.identifier === identifier) || {} + ).repeat; + + if (!expectedTimes) { + debug$4( + 'Route has been called at least once, and no expectation of more set:', + identifier + ); + return true; + } + const actualTimes = this.filterCalls(identifier).length; + + debug$4(`Route called ${actualTimes} times:`, identifier); + if (expectedTimes > actualTimes) { + debug$4( + `Route called ${actualTimes} times, but expected ${expectedTimes}:`, + identifier + ); + console.warn( + `Warning: ${identifier} only called ${actualTimes} times, but ${expectedTimes} expected` + ); // eslint-disable-line + return false; + } else { + return true; + } + }) + .every((isDone) => isDone); + + setDebugNamespace$1(); + setDebugPhase$2(); + return result; +}); + +var inspecting = FetchMock$2; + +const { debug: debug$5 } = debug_1; + + + + + +const FetchMock$3 = Object.assign({}, fetchHandler, setUpAndTearDown, inspecting); + +FetchMock$3.addMatcher = function (matcher) { + Route_1.addMatcher(matcher); +}; + +FetchMock$3.config = { + fallbackToNetwork: false, + includeContentLength: true, + sendAsJson: true, + warnOnFallback: true, + overwriteRoutes: undefined, +}; + +FetchMock$3.createInstance = function () { + debug$5('Creating fetch-mock instance'); + const instance = Object.create(FetchMock$3); + instance._uncompiledRoutes = (this._uncompiledRoutes || []).slice(); + instance.routes = instance._uncompiledRoutes.map((config) => + this.compileRoute(config) + ); + instance.fallbackResponse = this.fallbackResponse || undefined; + instance.config = Object.assign({}, this.config || FetchMock$3.config); + instance._calls = []; + instance._holdingPromises = []; + instance.bindMethods(); + return instance; +}; + +FetchMock$3.compileRoute = function (config) { + return new Route_1(config, this); +}; + +FetchMock$3.bindMethods = function () { + this.fetchHandler = FetchMock$3.fetchHandler.bind(this); + this.reset = this.restore = FetchMock$3.reset.bind(this); + this.resetHistory = FetchMock$3.resetHistory.bind(this); + this.resetBehavior = FetchMock$3.resetBehavior.bind(this); +}; + +FetchMock$3.sandbox = function () { + debug$5('Creating sandboxed fetch-mock instance'); + // this construct allows us to create a fetch-mock instance which is also + // a callable function, while circumventing circularity when defining the + // object that this function should be bound to + const fetchMockProxy = (url, options) => sandbox.fetchHandler(url, options); + + const sandbox = Object.assign( + fetchMockProxy, // Ensures that the entire returned object is a callable function + FetchMock$3, // prototype methods + this.createInstance(), // instance data + { + Headers: this.config.Headers, + Request: this.config.Request, + Response: this.config.Response, + } + ); + + sandbox.bindMethods(); + sandbox.isSandbox = true; + sandbox.default = sandbox; + return sandbox; +}; + +FetchMock$3.getOption = function (name, route = {}) { + return name in route ? route[name] : this.config[name]; +}; + +var lib = FetchMock$3; + +const statusTextMap = { + 100: 'Continue', + 101: 'Switching Protocols', + 102: 'Processing', + 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: 'Unordered Collection', + 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', +}; + +var statusText = statusTextMap; + +const theGlobal = typeof window !== 'undefined' ? window : self; +const { setUrlImplementation } = requestUtils; +setUrlImplementation(theGlobal.URL); + +lib.global = theGlobal; +lib.statusTextMap = statusText; + +lib.config = Object.assign(lib.config, { + Promise: theGlobal.Promise, + Request: theGlobal.Request, + Response: theGlobal.Response, + Headers: theGlobal.Headers, +}); + +var client = lib.createInstance(); + +export default client; diff --git a/esm/package.json b/esm/package.json new file mode 100644 index 00000000..6990891f --- /dev/null +++ b/esm/package.json @@ -0,0 +1 @@ +{"type": "module"} diff --git a/esm/server.d.ts b/esm/server.d.ts new file mode 100644 index 00000000..35d2bb99 --- /dev/null +++ b/esm/server.d.ts @@ -0,0 +1,697 @@ +// Project: https://github.com/wheresrhys/fetch-mock, http://www.wheresrhys.co.uk/fetch-mock +// Definitions by: Alexey Svetliakov +// Tamir Duberstein +// Risto Keravuori +// Chris Sinclair +// Matt Tennison +// Quentin Bouygues +// Fumiaki Matsushima +// Colin Doig +// Felix Chen +// Katsuya Hino +// +// Please note that I - wheresrys - don't use Typescript +// These types have ben copied in here as a convenience for (some of) +// fetch-mock's users +// If you are a Typescript user and find a problem in these types, please +// submit a PR +// +// TypeScript Version: 2.2 + +declare namespace fetchMock { + type MockRequest = Request | RequestInit; + + /** + * Mock matcher function + */ + type MockMatcherFunction = (url: string, opts: MockRequest) => boolean; + + + type MockMatcherUrl = string | RegExp; + + + /** + * Mock matcher. Can be one of following: + * string: Either + * * an exact url to match e.g. 'http://www.site.com/page.html' + * * if the string begins with a `^`, the string following the `^` must + * begin the url e.g. '^http://www.site.com' would match + * 'http://www.site.com' or 'http://www.site.com/page.html' + * * '*' to match any url + * RegExp: A regular expression to test the url against + * Function(url, opts): A function (returning a Boolean) that is passed the + * url and opts fetch() is called with (or, if fetch() was called with one, + * the Request instance) + */ + type MockMatcher = MockMatcherUrl | MockMatcherFunction; + + /** + * Inspection filter. Can be one of the following: + * boolean: + * * true retrieves all calls matched by fetch. + * fetchMock.MATCHED is an alias for true and may be used to make tests + * more readable. + * * false retrieves all calls not matched by fetch (i.e. those handled + * by catch() or spy(). fetchMock.UNMATCHED is an alias for false and + * may be used to make tests more readable. + * MockMatcher (routeIdentifier): + * All routes have an identifier: + * * If it’s a named route, the identifier is the route’s name + * * If the route is unnamed, the identifier is the matcher passed in to + * .mock() + * All calls that were handled by the route with the given identifier + * will be retrieved + * MockMatcher (matcher): + * Any matcher compatible with the mocking api can be passed in to filter + * the calls arbitrarily. + */ + type InspectionFilter = MockMatcher | boolean; + + /** + * Either an object compatible with the mocking api or a string specifying + * a http method to filter by. This will be used to filter the list of + * calls further. + */ + type InspectionOptions = MockOptions | string; + + /** + * Mock response object + */ + interface MockResponseObject { + /** + * Set the response body + */ + body?: string | {}; + + /** + * Set the response status + * @default 200 + */ + status?: number; + + /** + * Set the response headers. + */ + headers?: { [key: string]: string }; + + /** + * If this property is present then a Promise rejected with the value + * of throws is returned + */ + throws?: Error; + + /** + * The URL the response should be from (to imitate followed redirects + * - will set redirected: true on the response) + */ + redirectUrl?: string; + } + + /** + * Response: A Response instance - will be used unaltered + * number: Creates a response with this status + * string: Creates a 200 response with the string as the response body + * object: As long as the object is not a MockResponseObject it is + * converted into a json string and returned as the body of a 200 response + * If MockResponseObject was given then it's used to configure response + * Function(url, opts): A function that is passed the url and opts fetch() + * is called with and that returns any of the responses listed above + */ + type MockResponse = Response | Promise + | number | Promise + | string | Promise + | {} | Promise<{}> + | MockResponseObject | Promise; + + /** + * Mock response function + */ + type MockResponseFunction = (url: string, opts: MockRequest) => MockResponse; + + + /** + * Mock options object + */ + interface MockOptions { + /** + * A unique string naming the route. Used to subsequently retrieve + * references to the calls, grouped by name. + * @default matcher.toString() + * + * Note: If a non-unique name is provided no error will be thrown + * (because names are optional, auto-generated ones may legitimately + * clash) + */ + name?: string; + + /** + * http method to match + */ + method?: string; + + /** + * key/value map of headers to match + */ + headers?: { [key: string]: string | number }; + + /** + * key/value map of query strings to match, in any order + */ + query?: object; + + /** + * key/value map of express style path params to match + */ + params?: { [key: string]: string }; + + /** + * JSON serialisable object literal. Allowing any object for now + * But in typescript 3.7 will change to JSON + */ + body?: object; + + /** + * A function for arbitrary matching + */ + functionMatcher?: MockMatcherFunction; + + /** + * as specified above + */ + matcher?: MockMatcher; + + url?: MockMatcherUrl; + + /** + * This option allows for existing routes in a mock to be overwritten. + * It’s also possible to define multiple routes with ‘the same’ matcher. + * Default behaviour is to error + */ + overwriteRoutes?: boolean; + + /** + * as specified above + */ + response?: MockResponse | MockResponseFunction; + + /** + * integer, n, limiting the number of times the matcher can be used. + * If the route has already been called n times the route will be + * ignored and the call to fetch() will fall through to be handled by + * any other routes defined (which may eventually result in an error + * if nothing matches it). + */ + repeat?: number; + + /** + * integer, n, delays responding for the number of milliseconds + * specified. + */ + delay?: number; + + /** + * Convert objects into JSON before delivering as stub responses. Can + * be useful to set to false globally if e.g. dealing with a lot of + * array buffers. If true, will also add content-type: application/json + * header. + * @default true + */ + sendAsJson?: boolean; + + /** + * Automatically sets a content-length header on each response. + * @default true + */ + includeContentLength?: boolean; + + /** + * Match calls that only partially match a specified body json. + */ + matchPartialBody?: boolean; + } + + interface MockCall extends Array { + 0: string; + 1: RequestInit | undefined; + identifier: string; + isUnmatched: boolean | undefined; + request: Request | undefined; + response: Response | undefined; + } + + interface MockOptionsMethodGet extends MockOptions { + method?: 'GET'; + } + + interface MockOptionsMethodPost extends MockOptions { + method?: 'POST'; + } + + interface MockOptionsMethodPut extends MockOptions { + method?: 'PUT'; + } + + interface MockOptionsMethodDelete extends MockOptions { + method?: 'DELETE'; + } + + interface MockOptionsMethodPatch extends MockOptions { + method?: 'PATCH'; + } + + interface MockOptionsMethodHead extends MockOptions { + method?: 'HEAD'; + } + + interface FetchMockStatic { + MATCHED: true; + UNMATCHED: false; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Calls to .mock() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + mock(matcher: MockMatcher | MockOptions, response: MockResponse | MockResponseFunction, options?: MockOptions): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Calls to .mock() can be chained. + * @param options The route to mock + */ + mock(options: MockOptions): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Calls to .mock() can be chained. + * @param options The route to mock + */ + mock(): this; + + /** + * Returns a drop-in mock for fetch which can be passed to other mocking + * libraries. It implements the full fetch-mock api and maintains its + * own state independent of other instances, so tests can be run in + * parallel. + */ + sandbox(): FetchMockSandbox; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() limited to being + * called one time only. Calls to .once() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Optional additional properties defining the route to mock + */ + once(matcher: MockMatcher | MockOptions, response: MockResponse | MockResponseFunction, options?: MockOptions): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the GET + * method. Calls to .get() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + get(matcher: MockMatcher | MockOptionsMethodGet, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodGet): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the GET + * method and limited to being called one time only. Calls to .getOnce() + * can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + getOnce(matcher: MockMatcher | MockOptionsMethodGet, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodGet): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the POST + * method. Calls to .post() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + post(matcher: MockMatcher | MockOptionsMethodPost, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodPost): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the POST + * method and limited to being called one time only. Calls to .postOnce() + * can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + postOnce(matcher: MockMatcher | MockOptionsMethodPost, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodPost): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the PUT + * method. Calls to .put() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + put(matcher: MockMatcher | MockOptionsMethodPut, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodPut): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the PUT + * method and limited to being called one time only. Calls to .putOnce() + * can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + putOnce(matcher: MockMatcher | MockOptionsMethodPut, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodPut): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the + * DELETE method. Calls to .delete() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + delete(matcher: MockMatcher | MockOptionsMethodDelete, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodDelete): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the + * DELETE method and limited to being called one time only. Calls to + * .deleteOnce() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + deleteOnce(matcher: MockMatcher | MockOptionsMethodDelete, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodDelete): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the HEAD + * method. Calls to .head() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + head(matcher: MockMatcher | MockOptionsMethodHead, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodHead): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the HEAD + * method and limited to being called one time only. Calls to .headOnce() + * can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + headOnce(matcher: MockMatcher | MockOptionsMethodHead, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodHead): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the PATCH + * method. Calls to .patch() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + patch(matcher: MockMatcher | MockOptionsMethodPatch, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodPatch): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the PATCH + * method and limited to being called one time only. Calls to .patchOnce() + * can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + patchOnce(matcher: MockMatcher | MockOptionsMethodPatch, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodPatch): this; + + /** + * Chainable method that defines how to respond to calls to fetch that + * don't match any of the defined mocks. It accepts the same types of + * response as a normal call to .mock(matcher, response). It can also + * take an arbitrary function to completely customise behaviour of + * unmatched calls. If .catch() is called without any parameters then + * every unmatched call will receive a 200 response. + * @param [response] Configures the http response returned by the mock + */ + catch(response?: MockResponse | MockResponseFunction): this; + + /** + * Chainable method that records the call history of unmatched calls, + * but instead of responding with a stubbed response, the request is + * passed through to native fetch() and is allowed to communicate + * over the network. Similar to catch(). + */ + spy(response?: MockResponse | MockResponseFunction): this; + + /** + * Restores fetch() to its unstubbed state and clears all data recorded + * for its calls. reset() is an alias for restore(). + */ + restore(): this; + + /** + * Restores fetch() to its unstubbed state and clears all data recorded + * for its calls. reset() is an alias for restore(). + */ + reset(): this; + + /** + * Clears all data recorded for fetch()’s calls. It will not restore + * fetch to its default implementation. + */ + resetHistory(): this; + + /** + * Removes mocking behaviour without resetting call history. + */ + resetBehavior(): this; + + /** + * Returns a promise that resolves once all fetches handled by fetch-mock + * have resolved. + * @param [waitForBody] Wait for all body parsing methods(res.json(), + * res.text(), etc.) to resolve too. + */ + flush(waitForBody?: boolean): Promise; + + /** + * Returns an array of all calls to fetch matching the given filters. + * Each call is returned as a [url, options] array. If fetch was called + * using a Request instance, this will be available as a request + * property on this array. + * @param [filter] Allows filtering of calls to fetch based on various + * criteria + * @param [options] Either an object compatible with the mocking api or + * a string specifying a http method to filter by. This will be used to + * filter the list of calls further. + */ + calls(filter?: InspectionFilter, options?: InspectionOptions): MockCall[]; + + /** + * Returns a Boolean indicating whether any calls to fetch matched the + * given filter. + * @param [filter] Allows filtering of calls to fetch based on various + * criteria + * @param [options] Either an object compatible with the mocking api or + * a string specifying a http method to filter by. This will be used to + * filter the list of calls further. + */ + called(filter?: InspectionFilter, options?: InspectionOptions): boolean; + + /** + * Returns a Boolean indicating whether fetch was called the expected + * number of times (or has been called at least once if repeat is + * undefined for the route). + * @param [filter] Rule for matching calls to fetch. + */ + done(filter?: InspectionFilter): boolean; + + /** + * Returns the arguments for the last call to fetch matching the given + * filter. + * @param [filter] Allows filtering of calls to fetch based on various + * criteria + * @param [options] Either an object compatible with the mocking api or + * a string specifying a http method to filter by. This will be used to + * filter the list of calls further. + */ + lastCall( + filter?: InspectionFilter, + options?: InspectionOptions, + ): MockCall | undefined; + + /** + * Returns the url for the last call to fetch matching the given + * filter. If fetch was last called using a Request instance, the url + * will be extracted from this. + * @param [filter] Allows filtering of calls to fetch based on various + * criteria + * @param [options] Either an object compatible with the mocking api or + * a string specifying a http method to filter by. This will be used to + * filter the list of calls further. + */ + lastUrl( + filter?: InspectionFilter, + options?: InspectionOptions, + ): string | undefined; + + /** + * Returns the options for the call to fetch matching the given filter. + * If fetch was last called using a Request instance, a set of options + * inferred from the Request will be returned. + * @param [filter] Allows filtering of calls to fetch based on various + * criteria + * @param [options] Either an object compatible with the mocking api or + * a string specifying a http method to filter by. This will be used to + * filter the list of calls further. + */ + lastOptions( + filter?: InspectionFilter, + options?: InspectionOptions, + ): MockOptions | undefined; + + /** + * Returns the options for the call to fetch matching the given filter. + * This is an experimental feature, very difficult to implement well given + * fetch’s very private treatment of response bodies. + * When doing all the following: + - using node-fetch + - responding with a real network response (using spy() or fallbackToNetwork) + - using `fetchMock.LastResponse()` + - awaiting the body content + … the response will hang unless your source code also awaits the response body. + This is an unavoidable consequence of the nodejs implementation of streams. + * @param [filter] Allows filtering of calls to fetch based on various + * criteria + * @param [options] Either an object compatible with the mocking api or + * a string specifying a http method to filter by. This will be used to + * filter the list of calls further. + */ + lastResponse( + filter?: InspectionFilter, + options?: InspectionOptions, + ): Response | undefined; + + config: { + /** + * Convert objects into JSON before delivering as stub responses. + * Can be useful to set to false globally if e.g. dealing with a + * lot of array buffers. If true, will also add + * content-type: application/json header. + * @default true + */ + sendAsJson?: boolean; + + /** + * Automatically sets a content-length header on each response. + * @default true + */ + includeContentLength?: boolean; + + /** + * - true: Unhandled calls fall through to the network + * - false: Unhandled calls throw an error + * - 'always': All calls fall through to the network, effectively + * disabling fetch-mock. + * @default false + */ + fallbackToNetwork?: boolean | 'always'; + + /** + * Determines behaviour if a new route has the same name (or + * inferred name) as an existing one + * - undefined: An error will be throw when routes clash + * - true: Overwrites the existing route + * - false: Appends the new route to the list of routes + * @default undefined + */ + overwriteRoutes?: boolean; + + /** + * Print a warning if any call is caught by a fallback handler (set + * using the fallbackToNetwork option or catch()) + * @default true + */ + warnOnFallback?: boolean; + + /** + * Reference to the Promise constructor of a custom Promise + * implementation. + */ + Promise?: new (executor: ( + // Should be (value?: T | PromiseLike) => void + // But not sure if that's compatible with older typescript + resolve: (value?: any) => void, + reject: (value?: any) => void, + ) => void) => Promise; + + /** + * Reference to a custom fetch implementation. + */ + fetch?: ( + input?: string | Request, + init?: RequestInit, + ) => Promise; + + /** + * Reference to the Headers constructor of a custom fetch + * implementation. + */ + Headers?: new () => Headers; + + /** + * Reference to the Request constructor of a custom fetch + * implementation. + */ + Request?: new (input: string | Request, init?: RequestInit) => Request; + + /** + * Reference to the Response constructor of a custom fetch + * implementation. + */ + Response?: new () => Response; + }; + } + + interface FetchMockSandbox extends FetchMockStatic { + /** + * Also callable as fetch(). Use `typeof fetch` in your code to define + * a field that accepts both `fetch()` and a fetch-mock sandbox. + */ + (input?: string | Request , init?: RequestInit): Promise; + } +} + +declare var fetchMock: fetchMock.FetchMockStatic; +export = fetchMock; + +declare module 'fetch-mock/esm/client' { + const fetchMock: fetchMock.FetchMockStatic; + export default fetchMock; +} diff --git a/esm/server.js b/esm/server.js new file mode 100644 index 00000000..f9e560eb --- /dev/null +++ b/esm/server.js @@ -0,0 +1,26186 @@ +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +function getCjsExportFromNamespace (n) { + return n && n['default'] || n; +} + +var domain; + +// This constructor is used to store event handlers. Instantiating this is +// faster than explicitly calling `Object.create(null)` to get a "clean" empty +// object (tested with v8 v4.9). +function EventHandlers() {} +EventHandlers.prototype = Object.create(null); + +function EventEmitter() { + EventEmitter.init.call(this); +} + +// nodejs oddity +// require('events') === require('events').EventEmitter +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.usingDomains = false; + +EventEmitter.prototype.domain = undefined; +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; +}; + +function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); +}; + +// These standalone emit* functions are used to optimize calling of event +// handlers for fast cases because emit() itself often has a variable number of +// arguments and can be deoptimized because of that. These functions always have +// the same number of arguments and thus do not get deoptimized, so the code +// inside them can execute faster. +function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } +} +function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } +} +function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } +} +function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } +} + +function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } +} + +EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; +} +function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); +} +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; +} + +EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + +EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; +}; + +// About 1.5x faster than the two-arg version of Array#splice(). +function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); +} + +function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + +var lookup = []; +var revLookup = []; +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; +var inited = false; +function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; +} + +function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') +} + +function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') +} + +function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; +} + +var toString = {}.toString; + +var isArray = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +var INSPECT_MAX_BYTES = 50; + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer$1.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + +function kMaxLength () { + return Buffer$1.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer$1.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer$1(length); + } + that.length = length; + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer$1 (arg, encodingOrOffset, length) { + if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) { + return new Buffer$1(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer$1.poolSize = 8192; // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer$1._augment = function (arr) { + arr.__proto__ = Buffer$1.prototype; + return arr +}; + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer$1.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +}; + +if (Buffer$1.TYPED_ARRAY_SUPPORT) { + Buffer$1.prototype.__proto__ = Uint8Array.prototype; + Buffer$1.__proto__ = Uint8Array; +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer$1.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +}; + +function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer$1.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer$1.allocUnsafe = function (size) { + return allocUnsafe(null, size) +}; +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer$1.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +}; + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer$1.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that +} + +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer$1.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that +} + +function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} +Buffer$1.isBuffer = isBuffer; +function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer$1.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +Buffer$1.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +}; + +Buffer$1.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer$1.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer$1.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer +}; + +function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +} +Buffer$1.byteLength = byteLength; + +function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer$1.prototype._isBuffer = true; + +function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; +} + +Buffer$1.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this +}; + +Buffer$1.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this +}; + +Buffer$1.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this +}; + +Buffer$1.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +}; + +Buffer$1.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer$1.compare(this, b) === 0 +}; + +Buffer$1.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' +}; + +Buffer$1.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer$1.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer$1.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer$1.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +}; + +Buffer$1.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +}; + +Buffer$1.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +}; + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer$1.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +}; + +Buffer$1.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +}; + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000; + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res +} + +Buffer$1.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer$1.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer$1(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf +}; + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer$1.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val +}; + +Buffer$1.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val +}; + +Buffer$1.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] +}; + +Buffer$1.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) +}; + +Buffer$1.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] +}; + +Buffer$1.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +}; + +Buffer$1.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +}; + +Buffer$1.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer$1.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer$1.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +}; + +Buffer$1.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer$1.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer$1.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +}; + +Buffer$1.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +}; + +Buffer$1.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) +}; + +Buffer$1.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) +}; + +Buffer$1.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) +}; + +Buffer$1.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) +}; + +function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer$1.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer$1.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer$1.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 +}; + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } +} + +Buffer$1.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer$1.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } +} + +Buffer$1.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer$1.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +Buffer$1.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer$1.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer$1.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 +}; + +Buffer$1.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer$1.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +Buffer$1.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer$1.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 +} + +Buffer$1.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +}; + +Buffer$1.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +}; + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 +} + +Buffer$1.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +}; + +Buffer$1.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +}; + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer$1.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len +}; + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer$1.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer$1(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this +}; + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray +} + + +function base64ToBytes (str) { + return toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + + +// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +function isBuffer(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) +} + +function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) +} + +// shim for using process in browser +// based off https://github.com/defunctzombie/node-process/blob/master/browser.js + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +var cachedSetTimeout = defaultSetTimout; +var cachedClearTimeout = defaultClearTimeout; +if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; +} +if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; +} + +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} +function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +} +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +var title = 'browser'; +var platform = 'browser'; +var browser = true; +var env = {}; +var argv = []; +var version = ''; // empty string to avoid regexp issues +var versions = {}; +var release = {}; +var config = {}; + +function noop() {} + +var on = noop; +var addListener = noop; +var once = noop; +var off = noop; +var removeListener = noop; +var removeAllListeners = noop; +var emit = noop; + +function binding(name) { + throw new Error('process.binding is not supported'); +} + +function cwd () { return '/' } +function chdir (dir) { + throw new Error('process.chdir is not supported'); +}function umask() { return 0; } + +// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js +var performance = global$1.performance || {}; +var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + +// generate timestamp or delta +// see http://nodejs.org/api/process.html#process_process_hrtime +function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] +} + +var startTime = new Date(); +function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; +} + +var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime +}; + +var inherits; +if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; +} +var inherits$1 = inherits; + +var formatRegExp = /%[sdj%]/g; +function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +} + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + var warned = false; + function deprecated() { + if (!warned) { + { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +var debugs = {}; +var debugEnviron; +function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +} + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray$1(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray$1(ar) { + return Array.isArray(ar); +} + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} + +function isNull(arg) { + return arg === null; +} + +function isNullOrUndefined(arg) { + return arg == null; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isString(arg) { + return typeof arg === 'string'; +} + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} + +function isUndefined(arg) { + return arg === void 0; +} + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} + +function isBuffer$1(maybeBuf) { + return isBuffer(maybeBuf); +} + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +function log() { + console.log('%s - %s', timestamp(), format.apply(null, arguments)); +} + +function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +} +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +var util = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer$1, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray$1, + inspect: inspect, + deprecate: deprecate, + format: format, + debuglog: debuglog +}; + +function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; +} + +BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; +}; + +BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; +}; + +BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; +}; + +BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; +}; + +BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; +}; + +BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer$1.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer$1.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; +}; + +// Copyright Joyent, Inc. and other Node contributors. +var isBufferEncoding = Buffer$1.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer$1(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +} + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} + +Readable.ReadableState = ReadableState; + +var debug = debuglog('stream'); +inherits$1(Readable, EventEmitter); + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } +} +function listenerCount$1 (emitter, type) { + return emitter.listeners(type).length; +} +function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer$1.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount$1(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer$1.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} + +// A bit simpler than readable streams. +Writable.WritableState = WritableState; +inherits$1(Writable, EventEmitter); + +function nop() {} + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; +function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer$1.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer$1.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer$1.from(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer$1.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} + +function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; +} + +inherits$1(Duplex, Readable); + +var keys = Object.keys(Writable.prototype); +for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +// a transform stream is a readable/writable stream where you do +inherits$1(Transform, Duplex); + +function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} + +inherits$1(PassThrough, Transform); +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; + +inherits$1(Stream, EventEmitter); +Stream.Readable = Readable; +Stream.Writable = Writable; +Stream.Duplex = Duplex; +Stream.Transform = Transform; +Stream.PassThrough = PassThrough; + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EventEmitter.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + +var hasFetch = isFunction$1(global$1.fetch) && isFunction$1(global$1.ReadableStream); + +var _blobConstructor; +function blobConstructor() { + if (typeof _blobConstructor !== 'undefined') { + return _blobConstructor; + } + try { + new global$1.Blob([new ArrayBuffer(1)]); + _blobConstructor = true; + } catch (e) { + _blobConstructor = false; + } + return _blobConstructor +} +var xhr; + +function checkTypeSupport(type) { + if (!xhr) { + xhr = new global$1.XMLHttpRequest(); + // If location.host is empty, e.g. if this page/worker was loaded + // from a Blob, then use example.com to avoid an error + xhr.open('GET', global$1.location.host ? '/' : 'https://example.com'); + } + try { + xhr.responseType = type; + return xhr.responseType === type + } catch (e) { + return false + } + +} + +// For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'. +// Safari 7.1 appears to have fixed this bug. +var haveArrayBuffer = typeof global$1.ArrayBuffer !== 'undefined'; +var haveSlice = haveArrayBuffer && isFunction$1(global$1.ArrayBuffer.prototype.slice); + +var arraybuffer = haveArrayBuffer && checkTypeSupport('arraybuffer'); + // These next two tests unavoidably show warnings in Chrome. Since fetch will always + // be used if it's available, just return false for these to avoid the warnings. +var msstream = !hasFetch && haveSlice && checkTypeSupport('ms-stream'); +var mozchunkedarraybuffer = !hasFetch && haveArrayBuffer && + checkTypeSupport('moz-chunked-arraybuffer'); +var overrideMimeType = isFunction$1(xhr.overrideMimeType); +var vbArray = isFunction$1(global$1.VBArray); + +function isFunction$1(value) { + return typeof value === 'function' +} + +xhr = null; // Help gc + +var rStates = { + UNSENT: 0, + OPENED: 1, + HEADERS_RECEIVED: 2, + LOADING: 3, + DONE: 4 +}; +function IncomingMessage(xhr, response, mode) { + var self = this; + Readable.call(self); + + self._mode = mode; + self.headers = {}; + self.rawHeaders = []; + self.trailers = {}; + self.rawTrailers = []; + + // Fake the 'close' event, but only once 'end' fires + self.on('end', function() { + // The nextTick is necessary to prevent the 'request' module from causing an infinite loop + nextTick(function() { + self.emit('close'); + }); + }); + var read; + if (mode === 'fetch') { + self._fetchResponse = response; + + self.url = response.url; + self.statusCode = response.status; + self.statusMessage = response.statusText; + // backwards compatible version of for ( of ): + // for (var ,_i,_it = [Symbol.iterator](); = (_i = _it.next()).value,!_i.done;) + for (var header, _i, _it = response.headers[Symbol.iterator](); header = (_i = _it.next()).value, !_i.done;) { + self.headers[header[0].toLowerCase()] = header[1]; + self.rawHeaders.push(header[0], header[1]); + } + + // TODO: this doesn't respect backpressure. Once WritableStream is available, this can be fixed + var reader = response.body.getReader(); + + read = function () { + reader.read().then(function(result) { + if (self._destroyed) + return + if (result.done) { + self.push(null); + return + } + self.push(new Buffer$1(result.value)); + read(); + }); + }; + read(); + + } else { + self._xhr = xhr; + self._pos = 0; + + self.url = xhr.responseURL; + self.statusCode = xhr.status; + self.statusMessage = xhr.statusText; + var headers = xhr.getAllResponseHeaders().split(/\r?\n/); + headers.forEach(function(header) { + var matches = header.match(/^([^:]+):\s*(.*)/); + if (matches) { + var key = matches[1].toLowerCase(); + if (key === 'set-cookie') { + if (self.headers[key] === undefined) { + self.headers[key] = []; + } + self.headers[key].push(matches[2]); + } else if (self.headers[key] !== undefined) { + self.headers[key] += ', ' + matches[2]; + } else { + self.headers[key] = matches[2]; + } + self.rawHeaders.push(matches[1], matches[2]); + } + }); + + self._charset = 'x-user-defined'; + if (!overrideMimeType) { + var mimeType = self.rawHeaders['mime-type']; + if (mimeType) { + var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/); + if (charsetMatch) { + self._charset = charsetMatch[1].toLowerCase(); + } + } + if (!self._charset) + self._charset = 'utf-8'; // best guess + } + } +} + +inherits$1(IncomingMessage, Readable); + +IncomingMessage.prototype._read = function() {}; + +IncomingMessage.prototype._onXHRProgress = function() { + var self = this; + + var xhr = self._xhr; + + var response = null; + switch (self._mode) { + case 'text:vbarray': // For IE9 + if (xhr.readyState !== rStates.DONE) + break + try { + // This fails in IE8 + response = new global$1.VBArray(xhr.responseBody).toArray(); + } catch (e) { + // pass + } + if (response !== null) { + self.push(new Buffer$1(response)); + break + } + // Falls through in IE8 + case 'text': + try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4 + response = xhr.responseText; + } catch (e) { + self._mode = 'text:vbarray'; + break + } + if (response.length > self._pos) { + var newData = response.substr(self._pos); + if (self._charset === 'x-user-defined') { + var buffer = new Buffer$1(newData.length); + for (var i = 0; i < newData.length; i++) + buffer[i] = newData.charCodeAt(i) & 0xff; + + self.push(buffer); + } else { + self.push(newData, self._charset); + } + self._pos = response.length; + } + break + case 'arraybuffer': + if (xhr.readyState !== rStates.DONE || !xhr.response) + break + response = xhr.response; + self.push(new Buffer$1(new Uint8Array(response))); + break + case 'moz-chunked-arraybuffer': // take whole + response = xhr.response; + if (xhr.readyState !== rStates.LOADING || !response) + break + self.push(new Buffer$1(new Uint8Array(response))); + break + case 'ms-stream': + response = xhr.response; + if (xhr.readyState !== rStates.LOADING) + break + var reader = new global$1.MSStreamReader(); + reader.onprogress = function() { + if (reader.result.byteLength > self._pos) { + self.push(new Buffer$1(new Uint8Array(reader.result.slice(self._pos)))); + self._pos = reader.result.byteLength; + } + }; + reader.onload = function() { + self.push(null); + }; + // reader.onerror = ??? // TODO: this + reader.readAsArrayBuffer(response); + break + } + + // The ms-stream case handles end separately in reader.onload() + if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') { + self.push(null); + } +}; + +// from https://github.com/jhiesey/to-arraybuffer/blob/6502d9850e70ba7935a7df4ad86b358fc216f9f0/index.js +function toArrayBuffer (buf) { + // If the buffer is backed by a Uint8Array, a faster version will work + if (buf instanceof Uint8Array) { + // If the buffer isn't a subarray, return the underlying ArrayBuffer + if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) { + return buf.buffer + } else if (typeof buf.buffer.slice === 'function') { + // Otherwise we need to get a proper copy + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) + } + } + + if (isBuffer(buf)) { + // This is the slow version that will work with any Buffer + // implementation (even in old browsers) + var arrayCopy = new Uint8Array(buf.length); + var len = buf.length; + for (var i = 0; i < len; i++) { + arrayCopy[i] = buf[i]; + } + return arrayCopy.buffer + } else { + throw new Error('Argument must be a Buffer') + } +} + +function decideMode(preferBinary, useFetch) { + if (hasFetch && useFetch) { + return 'fetch' + } else if (mozchunkedarraybuffer) { + return 'moz-chunked-arraybuffer' + } else if (msstream) { + return 'ms-stream' + } else if (arraybuffer && preferBinary) { + return 'arraybuffer' + } else if (vbArray && preferBinary) { + return 'text:vbarray' + } else { + return 'text' + } +} + +function ClientRequest(opts) { + var self = this; + Writable.call(self); + + self._opts = opts; + self._body = []; + self._headers = {}; + if (opts.auth) + self.setHeader('Authorization', 'Basic ' + new Buffer$1(opts.auth).toString('base64')); + Object.keys(opts.headers).forEach(function(name) { + self.setHeader(name, opts.headers[name]); + }); + + var preferBinary; + var useFetch = true; + if (opts.mode === 'disable-fetch') { + // If the use of XHR should be preferred and includes preserving the 'content-type' header + useFetch = false; + preferBinary = true; + } else if (opts.mode === 'prefer-streaming') { + // If streaming is a high priority but binary compatibility and + // the accuracy of the 'content-type' header aren't + preferBinary = false; + } else if (opts.mode === 'allow-wrong-content-type') { + // If streaming is more important than preserving the 'content-type' header + preferBinary = !overrideMimeType; + } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') { + // Use binary if text streaming may corrupt data or the content-type header, or for speed + preferBinary = true; + } else { + throw new Error('Invalid value for opts.mode') + } + self._mode = decideMode(preferBinary, useFetch); + + self.on('finish', function() { + self._onFinish(); + }); +} + +inherits$1(ClientRequest, Writable); +// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method +var unsafeHeaders = [ + 'accept-charset', + 'accept-encoding', + 'access-control-request-headers', + 'access-control-request-method', + 'connection', + 'content-length', + 'cookie', + 'cookie2', + 'date', + 'dnt', + 'expect', + 'host', + 'keep-alive', + 'origin', + 'referer', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', + 'user-agent', + 'via' +]; +ClientRequest.prototype.setHeader = function(name, value) { + var self = this; + var lowerName = name.toLowerCase(); + // This check is not necessary, but it prevents warnings from browsers about setting unsafe + // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but + // http-browserify did it, so I will too. + if (unsafeHeaders.indexOf(lowerName) !== -1) + return + + self._headers[lowerName] = { + name: name, + value: value + }; +}; + +ClientRequest.prototype.getHeader = function(name) { + var self = this; + return self._headers[name.toLowerCase()].value +}; + +ClientRequest.prototype.removeHeader = function(name) { + var self = this; + delete self._headers[name.toLowerCase()]; +}; + +ClientRequest.prototype._onFinish = function() { + var self = this; + + if (self._destroyed) + return + var opts = self._opts; + + var headersObj = self._headers; + var body; + if (opts.method === 'POST' || opts.method === 'PUT' || opts.method === 'PATCH') { + if (blobConstructor()) { + body = new global$1.Blob(self._body.map(function(buffer) { + return toArrayBuffer(buffer) + }), { + type: (headersObj['content-type'] || {}).value || '' + }); + } else { + // get utf8 string + body = Buffer$1.concat(self._body).toString(); + } + } + + if (self._mode === 'fetch') { + var headers = Object.keys(headersObj).map(function(name) { + return [headersObj[name].name, headersObj[name].value] + }); + + global$1.fetch(self._opts.url, { + method: self._opts.method, + headers: headers, + body: body, + mode: 'cors', + credentials: opts.withCredentials ? 'include' : 'same-origin' + }).then(function(response) { + self._fetchResponse = response; + self._connect(); + }, function(reason) { + self.emit('error', reason); + }); + } else { + var xhr = self._xhr = new global$1.XMLHttpRequest(); + try { + xhr.open(self._opts.method, self._opts.url, true); + } catch (err) { + nextTick(function() { + self.emit('error', err); + }); + return + } + + // Can't set responseType on really old browsers + if ('responseType' in xhr) + xhr.responseType = self._mode.split(':')[0]; + + if ('withCredentials' in xhr) + xhr.withCredentials = !!opts.withCredentials; + + if (self._mode === 'text' && 'overrideMimeType' in xhr) + xhr.overrideMimeType('text/plain; charset=x-user-defined'); + + Object.keys(headersObj).forEach(function(name) { + xhr.setRequestHeader(headersObj[name].name, headersObj[name].value); + }); + + self._response = null; + xhr.onreadystatechange = function() { + switch (xhr.readyState) { + case rStates.LOADING: + case rStates.DONE: + self._onXHRProgress(); + break + } + }; + // Necessary for streaming in Firefox, since xhr.response is ONLY defined + // in onprogress, not in onreadystatechange with xhr.readyState = 3 + if (self._mode === 'moz-chunked-arraybuffer') { + xhr.onprogress = function() { + self._onXHRProgress(); + }; + } + + xhr.onerror = function() { + if (self._destroyed) + return + self.emit('error', new Error('XHR error')); + }; + + try { + xhr.send(body); + } catch (err) { + nextTick(function() { + self.emit('error', err); + }); + return + } + } +}; + +/** + * Checks if xhr.status is readable and non-zero, indicating no error. + * Even though the spec says it should be available in readyState 3, + * accessing it throws an exception in IE8 + */ +function statusValid(xhr) { + try { + var status = xhr.status; + return (status !== null && status !== 0) + } catch (e) { + return false + } +} + +ClientRequest.prototype._onXHRProgress = function() { + var self = this; + + if (!statusValid(self._xhr) || self._destroyed) + return + + if (!self._response) + self._connect(); + + self._response._onXHRProgress(); +}; + +ClientRequest.prototype._connect = function() { + var self = this; + + if (self._destroyed) + return + + self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode); + self.emit('response', self._response); +}; + +ClientRequest.prototype._write = function(chunk, encoding, cb) { + var self = this; + + self._body.push(chunk); + cb(); +}; + +ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function() { + var self = this; + self._destroyed = true; + if (self._response) + self._response._destroyed = true; + if (self._xhr) + self._xhr.abort(); + // Currently, there isn't a way to truly abort a fetch. + // If you like bikeshedding, see https://github.com/whatwg/fetch/issues/27 +}; + +ClientRequest.prototype.end = function(data, encoding, cb) { + var self = this; + if (typeof data === 'function') { + cb = data; + data = undefined; + } + + Writable.prototype.end.call(self, data, encoding, cb); +}; + +ClientRequest.prototype.flushHeaders = function() {}; +ClientRequest.prototype.setTimeout = function() {}; +ClientRequest.prototype.setNoDelay = function() {}; +ClientRequest.prototype.setSocketKeepAlive = function() {}; + +/*! https://mths.be/punycode v1.4.1 by @mathias */ + + +/** Highest positive signed 32-bit float value */ +var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +var base = 36; +var tMin = 1; +var tMax = 26; +var skew = 38; +var damp = 700; +var initialBias = 72; +var initialN = 128; // 0x80 +var delimiter = '-'; // '\x2D' + +/** Regular expressions */ +var regexPunycode = /^xn--/; +var regexNonASCII = /[^\x20-\x7E]/; // unprintable ASCII chars + non-ASCII chars +var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +var errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +var baseMinusTMin = base - tMin; +var floor = Math.floor; +var stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ +function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); +} + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; +} + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +} + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +} + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */ ) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */ ; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); +} + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */ ; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); +} + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) ? + decode(string.slice(4).toLowerCase()) : + string; + }); +} + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) ? + 'xn--' + encode(string) : + string; + }); +} +var version$1 = '1.4.1'; +/** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + +var ucs2 = { + decode: ucs2decode, + encode: ucs2encode +}; +var punycode = { + version: version$1, + ucs2: ucs2, + toASCII: toASCII, + toUnicode: toUnicode, + encode: encode, + decode: decode +}; + +// 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. + + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty$1(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} +var isArray$2 = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; +function stringifyPrimitive(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +} + +function stringify (obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map$1(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray$2(obj[k])) { + return map$1(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +} +function map$1 (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +function parse(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty$1(obj, k)) { + obj[k] = v; + } else if (isArray$2(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}var querystring = { + encode: stringify, + stringify: stringify, + decode: parse, + parse: parse +}; + +// Copyright Joyent, Inc. and other Node contributors. +var Url = { + parse: urlParse, + resolve: urlResolve, + resolveObject: urlResolveObject, + format: urlFormat, + Url: Url$1 +}; +function Url$1() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }; + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && isObject(url) && url instanceof Url$1) return url; + + var u = new Url$1; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} +Url$1.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + return parse$1(this, url, parseQueryString, slashesDenoteHost); +}; + +function parse$1(self, url, parseQueryString, slashesDenoteHost) { + if (!isString(url)) { + throw new TypeError('Parameter \'url\' must be a string, not ' + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + self.path = rest; + self.href = rest; + self.pathname = simplePath[1]; + if (simplePath[2]) { + self.search = simplePath[2]; + if (parseQueryString) { + self.query = parse(self.search.substr(1)); + } else { + self.query = self.search.substr(1); + } + } else if (parseQueryString) { + self.search = ''; + self.query = {}; + } + return self; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + self.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + self.slashes = true; + } + } + var i, hec, l, p; + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (i = 0; i < hostEndingChars.length; i++) { + hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + self.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (i = 0; i < nonHostChars.length; i++) { + hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + self.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + parseHost(self); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + self.hostname = self.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = self.hostname[0] === '[' && + self.hostname[self.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = self.hostname.split(/\./); + for (i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + self.hostname = validParts.join('.'); + break; + } + } + } + } + + if (self.hostname.length > hostnameMaxLen) { + self.hostname = ''; + } else { + // hostnames are always lower case. + self.hostname = self.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + self.hostname = toASCII(self.hostname); + } + + p = self.port ? ':' + self.port : ''; + var h = self.hostname || ''; + self.host = h + p; + self.href += self.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + self.hostname = self.hostname.substr(1, self.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + self.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + self.search = rest.substr(qm); + self.query = rest.substr(qm + 1); + if (parseQueryString) { + self.query = parse(self.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + self.search = ''; + self.query = {}; + } + if (rest) self.pathname = rest; + if (slashedProtocol[lowerProto] && + self.hostname && !self.pathname) { + self.pathname = '/'; + } + + //to support http.request + if (self.pathname || self.search) { + p = self.pathname || ''; + var s = self.search || ''; + self.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + self.href = format$1(self); + return self; +} + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (isString(obj)) obj = parse$1({}, obj); + return format$1(obj); +} + +function format$1(self) { + var auth = self.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = self.protocol || '', + pathname = self.pathname || '', + hash = self.hash || '', + host = false, + query = ''; + + if (self.host) { + host = auth + self.host; + } else if (self.hostname) { + host = auth + (self.hostname.indexOf(':') === -1 ? + self.hostname : + '[' + this.hostname + ']'); + if (self.port) { + host += ':' + self.port; + } + } + + if (self.query && + isObject(self.query) && + Object.keys(self.query).length) { + query = stringify(self.query); + } + + var search = self.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (self.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +} + +Url$1.prototype.format = function() { + return format$1(this); +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url$1.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url$1.prototype.resolveObject = function(relative) { + if (isString(relative)) { + var rel = new Url$1(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url$1(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + var relPath; + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + relPath = relative.pathname && relative.pathname.split('/') || []; + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + var authInHost; + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!isNull(result.pathname) || !isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!isNull(result.pathname) || !isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url$1.prototype.parseHost = function() { + return parseHost(this); +}; + +function parseHost(self) { + var host = self.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + self.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) self.hostname = host; +} + +function request(opts, cb) { + if (typeof opts === 'string') + opts = urlParse(opts); + + + // Normally, the page is loaded from http or https, so not specifying a protocol + // will result in a (valid) protocol-relative url. However, this won't work if + // the protocol is something else, like 'file:' + var defaultProtocol = global$1.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''; + + var protocol = opts.protocol || defaultProtocol; + var host = opts.hostname || opts.host; + var port = opts.port; + var path = opts.path || '/'; + + // Necessary for IPv6 addresses + if (host && host.indexOf(':') !== -1) + host = '[' + host + ']'; + + // This may be a relative url. The browser should always be able to interpret it correctly. + opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path; + opts.method = (opts.method || 'GET').toUpperCase(); + opts.headers = opts.headers || {}; + + // Also valid opts.auth, opts.mode + + var req = new ClientRequest(opts); + if (cb) + req.on('response', cb); + return req +} + +function get(opts, cb) { + var req = request(opts, cb); + req.end(); + return req +} + +function Agent() {} +Agent.defaultMaxSockets = 4; + +var METHODS = [ + 'CHECKOUT', + 'CONNECT', + 'COPY', + 'DELETE', + 'GET', + 'HEAD', + 'LOCK', + 'M-SEARCH', + 'MERGE', + 'MKACTIVITY', + 'MKCOL', + 'MOVE', + 'NOTIFY', + 'OPTIONS', + 'PATCH', + 'POST', + 'PROPFIND', + 'PROPPATCH', + 'PURGE', + 'PUT', + 'REPORT', + 'SEARCH', + 'SUBSCRIBE', + 'TRACE', + 'UNLOCK', + 'UNSUBSCRIBE' +]; +var STATUS_CODES = { + 100: 'Continue', + 101: 'Switching Protocols', + 102: 'Processing', // RFC 2518, obsoleted by RFC 4918 + 200: 'OK', + 201: 'Created', + 202: 'Accepted', + 203: 'Non-Authoritative Information', + 204: 'No Content', + 205: 'Reset Content', + 206: 'Partial Content', + 207: 'Multi-Status', // RFC 4918 + 300: 'Multiple Choices', + 301: 'Moved Permanently', + 302: 'Moved Temporarily', + 303: 'See Other', + 304: 'Not Modified', + 305: 'Use Proxy', + 307: 'Temporary 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 Time-out', + 409: 'Conflict', + 410: 'Gone', + 411: 'Length Required', + 412: 'Precondition Failed', + 413: 'Request Entity Too Large', + 414: 'Request-URI Too Large', + 415: 'Unsupported Media Type', + 416: 'Requested Range Not Satisfiable', + 417: 'Expectation Failed', + 418: 'I\'m a teapot', // RFC 2324 + 422: 'Unprocessable Entity', // RFC 4918 + 423: 'Locked', // RFC 4918 + 424: 'Failed Dependency', // RFC 4918 + 425: 'Unordered Collection', // RFC 4918 + 426: 'Upgrade Required', // RFC 2817 + 428: 'Precondition Required', // RFC 6585 + 429: 'Too Many Requests', // RFC 6585 + 431: 'Request Header Fields Too Large', // RFC 6585 + 500: 'Internal Server Error', + 501: 'Not Implemented', + 502: 'Bad Gateway', + 503: 'Service Unavailable', + 504: 'Gateway Time-out', + 505: 'HTTP Version Not Supported', + 506: 'Variant Also Negotiates', // RFC 2295 + 507: 'Insufficient Storage', // RFC 4918 + 509: 'Bandwidth Limit Exceeded', + 510: 'Not Extended', // RFC 2774 + 511: 'Network Authentication Required' // RFC 6585 +}; + +var http = { + request, + get, + Agent, + METHODS, + STATUS_CODES +}; + +var msg = { + 2: 'need dictionary', /* Z_NEED_DICT 2 */ + 1: 'stream end', /* Z_STREAM_END 1 */ + 0: '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ +}; + +function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} + +function arraySet(dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + // Fallback to ordinary array + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } +} + + +var Buf8 = Uint8Array; +var Buf16 = Uint16Array; +var Buf32 = Int32Array; +// Enable/Disable typed arrays use, for testing +// + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +//var Z_FILTERED = 1; +//var Z_HUFFMAN_ONLY = 2; +//var Z_RLE = 3; +var Z_FIXED = 4; +//var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +var Z_BINARY = 0; +var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + +/*============================================================================*/ + + +function zero(buf) { + var len = buf.length; + while (--len >= 0) { + buf[len] = 0; + } +} + +// From zutil.h + +var STORED_BLOCK = 0; +var STATIC_TREES = 1; +var DYN_TREES = 2; +/* The three kinds of block type */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +/* The minimum and maximum match lengths */ + +// From deflate.h +/* =========================================================================== + * Internal compression state. + */ + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ + +var LITERALS = 256; +/* number of literal bytes 0..255 */ + +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ + +var D_CODES = 30; +/* number of distance codes */ + +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ + +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ + +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var Buf_size = 16; +/* size of bit buffer in bi_buf */ + + +/* =========================================================================== + * Constants + */ + +var MAX_BL_BITS = 7; +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +var END_BLOCK = 256; +/* end of block literal code */ + +var REP_3_6 = 16; +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +var REPZ_3_10 = 17; +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +var REPZ_11_138 = 18; +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +/* eslint-disable comma-spacing,array-bracket-spacing */ +var extra_lbits = /* extra bits for each length code */ [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0]; + +var extra_dbits = /* extra bits for each distance code */ [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13]; + +var extra_blbits = /* extra bits for each bit length code */ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7]; + +var bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; +/* eslint-enable comma-spacing,array-bracket-spacing */ + +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +// We pre-fill arrays with 0 to avoid uninitialized gaps + +var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + +// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 +var static_ltree = new Array((L_CODES + 2) * 2); +zero(static_ltree); +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +var static_dtree = new Array(D_CODES * 2); +zero(static_dtree); +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +var _dist_code = new Array(DIST_CODE_LEN); +zero(_dist_code); +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); +zero(_length_code); +/* length code for each normalized match length (0 == MIN_MATCH) */ + +var base_length = new Array(LENGTH_CODES); +zero(base_length); +/* First normalized length for each code (0 = MIN_MATCH) */ + +var base_dist = new Array(D_CODES); +zero(base_dist); +/* First normalized distance for each code (0 = distance of 1) */ + + +function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; +} + + +var static_l_desc; +var static_d_desc; +var static_bl_desc; + + +function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ +} + + + +function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; +} + + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +function put_short(s, w) { + // put_byte(s, (uch)((w) & 0xff)); + // put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; +} + + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +function send_bits(s, value, length) { + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } +} + + +function send_code(s, c, tree) { + send_bits(s, tree[c * 2] /*.Code*/ , tree[c * 2 + 1] /*.Len*/ ); +} + + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; +} + + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } +} + + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +function gen_bitlen(s, desc) { +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max] * 2 + 1] /*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1] /*.Dad*/ * 2 + 1] /*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1] /*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { + continue; + } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2] /*.Freq*/ ; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1] /*.Len*/ + xbits); + } + } + if (overflow === 0) { + return; + } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { + bits--; + } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { + continue; + } + if (tree[m * 2 + 1] /*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m * 2 + 1] /*.Len*/ ) * tree[m * 2] /*.Freq*/ ; + tree[m * 2 + 1] /*.Len*/ = bits; + } + n--; + } + } +} + + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +function gen_codes(tree, max_code, bl_count) { +// ct_data *tree; /* the tree to decorate */ +// int max_code; /* largest code with non zero frequency */ +// ushf *bl_count; /* number of codes at each bit length */ + + var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits - 1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES - 1; code++) { + base_length[code] = length; + for (n = 0; n < (1 << extra_lbits[code]); n++) { + _length_code[length++] = code; + } + } + //Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length - 1] = code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1 << extra_dbits[code]); n++) { + _dist_code[dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1] /*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1] /*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1] /*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1] /*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES + 1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n * 2 + 1] /*.Len*/ = 5; + static_dtree[n * 2] /*.Code*/ = bi_reverse(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + + //static_init_done = true; +} + + +/* =========================================================================== + * Initialize a new block. + */ +function init_block(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) { + s.dyn_ltree[n * 2] /*.Freq*/ = 0; + } + for (n = 0; n < D_CODES; n++) { + s.dyn_dtree[n * 2] /*.Freq*/ = 0; + } + for (n = 0; n < BL_CODES; n++) { + s.bl_tree[n * 2] /*.Freq*/ = 0; + } + + s.dyn_ltree[END_BLOCK * 2] /*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; +} + + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +function bi_windup(s) { + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +function copy_block(s, buf, len, header) { +//DeflateState *s; +//charf *buf; /* the input data */ +//unsigned len; /* its length */ +//int header; /* true if block header must be written */ + + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, len); + put_short(s, ~len); + } + // while (len--) { + // put_byte(s, *buf++); + // } + arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return (tree[_n2] /*.Freq*/ < tree[_m2] /*.Freq*/ || + (tree[_n2] /*.Freq*/ === tree[_m2] /*.Freq*/ && depth[n] <= depth[m])); +} + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +function pqdownheap(s, tree, k) +// deflate_state *s; +// ct_data *tree; /* the tree to restore */ +// int k; /* node to move down */ +{ + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { + break; + } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; +} + + +// inlined manually +// var SMALLEST = 1; + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +function compress_block(s, ltree, dtree) +// deflate_state *s; +// const ct_data *ltree; /* literal tree */ +// const ct_data *dtree; /* distance tree */ +{ + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code(s, END_BLOCK, ltree); +} + + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +function build_tree(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n * 2] /*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n * 2 + 1] /*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2] /*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node * 2 + 1] /*.Len*/ ; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1 /*int /2*/ ); n >= 1; n--) { + pqdownheap(s, tree, n); + } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1 /*SMALLEST*/ ]; + s.heap[1 /*SMALLEST*/ ] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1 /*SMALLEST*/ ); + /***/ + + m = s.heap[1 /*SMALLEST*/ ]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2] /*.Freq*/ = tree[n * 2] /*.Freq*/ + tree[m * 2] /*.Freq*/ ; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1] /*.Dad*/ = tree[m * 2 + 1] /*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1 /*SMALLEST*/ ] = node++; + pqdownheap(s, tree, 1 /*SMALLEST*/ ); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1 /*SMALLEST*/ ]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); +} + + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +function scan_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1] /*.Len*/ ; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1] /*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1] /*.Len*/ ; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2] /*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { + s.bl_tree[curlen * 2] /*.Freq*/ ++; + } + s.bl_tree[REP_3_6 * 2] /*.Freq*/ ++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2] /*.Freq*/ ++; + + } else { + s.bl_tree[REPZ_11_138 * 2] /*.Freq*/ ++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +function send_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1] /*.Len*/ ; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ + /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1] /*.Len*/ ; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { + send_code(s, curlen, s.bl_tree); + } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +function build_bl_tree(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1] /*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; +} + + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +function send_all_trees(s, lcodes, dcodes, blcodes) +// deflate_state *s; +// int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1] /*.Len*/ , 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +function detect_data_type(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n * 2] /*.Freq*/ !== 0)) { + return Z_BINARY; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2] /*.Freq*/ !== 0 || s.dyn_ltree[10 * 2] /*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2] /*.Freq*/ !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2] /*.Freq*/ !== 0) { + return Z_TEXT; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + + +var static_init_done = false; + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +function _tr_init(s) { + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); +} + + +/* =========================================================================== + * Send a stored block + */ +function _tr_stored_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ + copy_block(s, buf, stored_len, true); /* with header */ +} + + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); +} + + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +function _tr_flush_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block, or NULL if too old */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len + 3 + 7) >>> 3; + static_lenb = (s.static_len + 3 + 7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { + opt_lenb = static_lenb; + } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +function _tr_tally(s, dist, lc) +// deflate_state *s; +// unsigned dist; /* distance of matched string */ +// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc * 2] /*.Freq*/ ++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2] /*.Freq*/ ++; + s.dyn_dtree[d_code(dist) * 2] /*.Freq*/ ++; + } + + // (!) This block is disabled in zlib defailts, + // don't enable it for binary compatibility + + //#ifdef TRUNCATE_BLOCK + // /* Try to guess if it is profitable to stop the current block here */ + // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { + // /* Compute an upper bound for the compressed length */ + // out_length = s.last_lit*8; + // in_length = s.strstart - s.block_start; + // + // for (dcode = 0; dcode < D_CODES; dcode++) { + // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); + // } + // out_length >>>= 3; + // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", + // // s->last_lit, in_length, out_length, + // // 100L - out_length*100L/in_length)); + // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { + // return true; + // } + // } + //#endif + + return (s.last_lit === s.lit_bufsize - 1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It doesn't worth to make additional optimizationa as in original. +// Small size is preferable. + +function adler32(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +} + +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + + +// Use ordinary array, since untyped makes no boost here +function makeTable() { + var c, table = []; + + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +} + +// Create table on load. Just 255 signed longs. Not a problem. +var crcTable = makeTable(); + + +function crc32(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc ^= -1; + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +} + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +var Z_NO_FLUSH = 0; +var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +//var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +//var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +//var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + + +/* compression levels */ +//var Z_NO_COMPRESSION = 0; +//var Z_BEST_SPEED = 1; +//var Z_BEST_COMPRESSION = 9; +var Z_DEFAULT_COMPRESSION = -1; + + +var Z_FILTERED = 1; +var Z_HUFFMAN_ONLY = 2; +var Z_RLE = 3; +var Z_FIXED$1 = 4; + +/* Possible values of the data_type field (though see inflate()) */ +//var Z_BINARY = 0; +//var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN$1 = 2; + + +/* The deflate compression method */ +var Z_DEFLATED = 8; + +/*============================================================================*/ + + +var MAX_MEM_LEVEL = 9; + + +var LENGTH_CODES$1 = 29; +/* number of length codes, not counting the special END_BLOCK code */ +var LITERALS$1 = 256; +/* number of literal bytes 0..255 */ +var L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1; +/* number of Literal or Length codes, including the END_BLOCK code */ +var D_CODES$1 = 30; +/* number of distance codes */ +var BL_CODES$1 = 19; +/* number of codes used to transfer the bit lengths */ +var HEAP_SIZE$1 = 2 * L_CODES$1 + 1; +/* maximum heap size */ +var MAX_BITS$1 = 15; +/* All codes must not exceed MAX_BITS bits */ + +var MIN_MATCH$1 = 3; +var MAX_MATCH$1 = 258; +var MIN_LOOKAHEAD = (MAX_MATCH$1 + MIN_MATCH$1 + 1); + +var PRESET_DICT = 0x20; + +var INIT_STATE = 42; +var EXTRA_STATE = 69; +var NAME_STATE = 73; +var COMMENT_STATE = 91; +var HCRC_STATE = 103; +var BUSY_STATE = 113; +var FINISH_STATE = 666; + +var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ +var BS_BLOCK_DONE = 2; /* block flush performed */ +var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ +var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + +var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. + +function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; +} + +function rank(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); +} + +function zero$1(buf) { + var len = buf.length; + while (--len >= 0) { + buf[len] = 0; + } +} + + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ +function flush_pending(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { + return; + } + + arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } +} + + +function flush_block_only(s, last) { + _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); +} + + +function put_byte(s, b) { + s.pending_buf[s.pending++] = b; +} + + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +function putShortMSB(s, b) { + // put_byte(s, (Byte)(b >> 8)); + // put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; +} + + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ +function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { + len = size; + } + if (len === 0) { + return 0; + } + + strm.avail_in -= len; + + // zmemcpy(buf, strm->next_in, len); + arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; +} + + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0 /*NIL*/ ; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH$1; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { + nice_match = s.lookahead; + } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH$1 - (strend - scan); + scan = strend - MAX_MATCH$1; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; +} + + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + + arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH$1) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; + //#if MIN_MATCH != 3 + // Call update_hash() MIN_MATCH-3 more times + //#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH$1 - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH$1) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ + // if (s.high_water < s.window_size) { + // var curr = s.strstart + s.lookahead; + // var init = 0; + // + // if (s.high_water < curr) { + // /* Previous high water mark below current data -- zero WIN_INIT + // * bytes or up to end of window, whichever is less. + // */ + // init = s.window_size - curr; + // if (init > WIN_INIT) + // init = WIN_INIT; + // zmemzero(s->window + curr, (unsigned)init); + // s->high_water = curr + init; + // } + // else if (s->high_water < (ulg)curr + WIN_INIT) { + // /* High water mark at or above current data, but below current data + // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up + // * to end of window, whichever is less. + // */ + // init = (ulg)curr + WIN_INIT - s->high_water; + // if (init > s->window_size - s->high_water) + // init = s->window_size - s->high_water; + // zmemzero(s->window + s->high_water, (unsigned)init); + // s->high_water += init; + // } + // } + // + // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, + // "not enough room for search"); +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +function deflate_stored(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); + // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || + // s.block_start >= s.w_size)) { + // throw new Error("slide too late"); + // } + + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); + // if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_NEED_MORE; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +function deflate_fast(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0 /*NIL*/ ; + if (s.lookahead >= MIN_MATCH$1) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0 /*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH$1) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$1); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match /*max_insert_length*/ && s.lookahead >= MIN_MATCH$1) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + + //#if MIN_MATCH != 3 + // Call UPDATE_HASH() MIN_MATCH-3 more times + //#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = _tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH$1 - 1)) ? s.strstart : MIN_MATCH$1 - 1); + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +function deflate_slow(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ + + var max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0 /*NIL*/ ; + if (s.lookahead >= MIN_MATCH$1) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH$1 - 1; + + if (hash_head !== 0 /*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD) /*MAX_DIST(s)*/ ) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH$1 && s.strstart - s.match_start > 4096 /*TOO_FAR*/ ))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH$1 - 1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH$1 && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH$1; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$1); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH$1 - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH$1 - 1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = _tr_tally(s, 0, s.window[s.strstart - 1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = _tr_tally(s, 0, s.window[s.strstart - 1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH$1 - 1 ? s.strstart : MIN_MATCH$1 - 1; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_BLOCK_DONE; +} + + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +function deflate_rle(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH$1) { + fill_window(s); + if (s.lookahead <= MAX_MATCH$1 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH$1 && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH$1; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH$1 - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH$1) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH$1); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = _tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +function deflate_huff(s, flush) { + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = _tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; +} + +var configuration_table; + +configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + + new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ +]; + + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +function lm_init(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero$1(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH$1 - 1; + s.match_available = 0; + s.ins_h = 0; +} + + +function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new Buf16(HEAP_SIZE$1 * 2); + this.dyn_dtree = new Buf16((2 * D_CODES$1 + 1) * 2); + this.bl_tree = new Buf16((2 * BL_CODES$1 + 1) * 2); + zero$1(this.dyn_ltree); + zero$1(this.dyn_dtree); + zero$1(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new Buf16(MAX_BITS$1 + 1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new Buf16(2 * L_CODES$1 + 1); /* heap used to build the Huffman trees */ + zero$1(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all + */ + + this.depth = new Buf16(2 * L_CODES$1 + 1); //uch depth[2*L_CODES+1]; + zero$1(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ +} + + +function deflateResetKeep(strm) { + var s; + + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN$1; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE : BUSY_STATE); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH; + _tr_init(s); + return Z_OK; +} + + +function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; +} + + +function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED$1) { + return err(strm, Z_STREAM_ERROR); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState(); + + strm.state = s; + s.strm = strm; + + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH$1 - 1) / MIN_MATCH$1); + + s.window = new Buf8(s.w_size * 2); + s.head = new Buf16(s.hash_size); + s.prev = new Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + + //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + //s->pending_buf = (uchf *) overlay; + s.pending_buf = new Buf8(s.pending_buf_size); + + // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) + //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s.d_buf = 1 * s.lit_bufsize; + + //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset(strm); +} + + +function deflate(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE && flush !== Z_FINISH)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE) { + if (s.wrap === 2) { + // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } else // DEFLATE header + { + var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { + header |= PRESET_DICT; + } + header += 31 - (header % 31); + + s.status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + + //#ifdef GZIP + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra /* != Z_NULL*/ ) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name /* != Z_NULL*/ ) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment /* != Z_NULL*/ ) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + } + } else { + s.status = BUSY_STATE; + } + } + //#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : + (s.strategy === Z_RLE ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + _tr_align(s); + } else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + + _tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH) { + /*** CLEAR_HASH(s); ***/ + /* forget history */ + zero$1(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH) { + return Z_OK; + } + if (s.wrap <= 0) { + return Z_STREAM_END; + } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } else { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { + s.wrap = -s.wrap; + } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK : Z_STREAM_END; +} + +function deflateEnd(strm) { + var status; + + if (!strm /*== Z_NULL*/ || !strm.state /*== Z_NULL*/ ) { + return Z_STREAM_ERROR; + } + + status = strm.state.status; + if (status !== INIT_STATE && + status !== EXTRA_STATE && + status !== NAME_STATE && + status !== COMMENT_STATE && + status !== HCRC_STATE && + status !== BUSY_STATE && + status !== FINISH_STATE + ) { + return err(strm, Z_STREAM_ERROR); + } + + strm.state = null; + + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; +} + +/* Not implemented +exports.deflateBound = deflateBound; +exports.deflateCopy = deflateCopy; +exports.deflateParams = deflateParams; +exports.deflatePending = deflatePending; +exports.deflatePrime = deflatePrime; +exports.deflateTune = deflateTune; +*/ + +// See state defs from inflate.js +var BAD = 30; /* got a data error -- remain here until reset */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ +function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ +//#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ +//#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); +//#ifdef INFLATE_STRICT + dmax = state.dmax; +//#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); +//#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } +//#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } + +// (!) This block is disabled in zlib defailts, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// if (len <= op - whave) { +// do { +// output[_out++] = 0; +// } while (--len); +// continue top; +// } +// len -= op - whave; +// do { +// output[_out++] = 0; +// } while (--op > whave); +// if (op === 0) { +// from = _out - dist; +// do { +// output[_out++] = output[from++]; +// } while (--len); +// continue top; +// } +//#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; +} + +var MAXBITS = 15; +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +var lbase = [ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 +]; + +var lext = [ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 +]; + +var dbase = [ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 +]; + +var dext = [ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 +]; + +function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, + max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; + // var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { + break; + } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { + break; + } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val | 0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { + break; + } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { + break; + } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) | 0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) | 0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; +} + +var CODES$1 = 0; +var LENS$1 = 1; +var DISTS$1 = 2; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +//var Z_NO_FLUSH = 0; +//var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +//var Z_FULL_FLUSH = 3; +var Z_FINISH$1 = 4; +var Z_BLOCK$1 = 5; +var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK$1 = 0; +var Z_STREAM_END$1 = 1; +var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR$1 = -2; +var Z_DATA_ERROR$1 = -3; +var Z_MEM_ERROR = -4; +var Z_BUF_ERROR$1 = -5; +//var Z_VERSION_ERROR = -6; + +/* The deflate compression method */ +var Z_DEFLATED$1 = 8; + + +/* STATES ====================================================================*/ +/* ===========================================================================*/ + + +var HEAD = 1; /* i: waiting for magic header */ +var FLAGS = 2; /* i: waiting for method and flags (gzip) */ +var TIME = 3; /* i: waiting for modification time (gzip) */ +var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ +var EXLEN = 5; /* i: waiting for extra length (gzip) */ +var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ +var NAME = 7; /* i: waiting for end of file name (gzip) */ +var COMMENT = 8; /* i: waiting for end of comment (gzip) */ +var HCRC = 9; /* i: waiting for header crc (gzip) */ +var DICTID = 10; /* i: waiting for dictionary check value */ +var DICT = 11; /* waiting for inflateSetDictionary() call */ +var TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */ +var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ +var STORED = 14; /* i: waiting for stored size (length and complement) */ +var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ +var COPY = 16; /* i/o: waiting for input or output to copy stored block */ +var TABLE = 17; /* i: waiting for dynamic block table lengths */ +var LENLENS = 18; /* i: waiting for code length code lengths */ +var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ +var LEN_ = 20; /* i: same as LEN below, but only first time in */ +var LEN = 21; /* i: waiting for length/lit/eob code */ +var LENEXT = 22; /* i: waiting for length extra bits */ +var DIST = 23; /* i: waiting for distance code */ +var DISTEXT = 24; /* i: waiting for distance extra bits */ +var MATCH = 25; /* o: waiting for output space to copy string */ +var LIT = 26; /* o: waiting for output space to write literal */ +var CHECK = 27; /* i: waiting for 32-bit check value */ +var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ +var DONE = 29; /* finished check, done -- remain here until reset */ +var BAD$1 = 30; /* got a data error -- remain here until reset */ +var MEM = 31; /* got an inflate() memory error -- remain here until reset */ +var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ + +/* ===========================================================================*/ + + + +var ENOUGH_LENS$1 = 852; +var ENOUGH_DISTS$1 = 592; + + +function zswap32(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); +} + + +function InflateState() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new Buf16(320); /* temporary storage for code lengths */ + this.work = new Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ +} + +function inflateResetKeep(strm) { + var state; + + if (!strm || !strm.state) { + return Z_STREAM_ERROR$1; + } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null /*Z_NULL*/ ; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new Buf32(ENOUGH_LENS$1); + state.distcode = state.distdyn = new Buf32(ENOUGH_DISTS$1); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK$1; +} + +function inflateReset(strm) { + var state; + + if (!strm || !strm.state) { + return Z_STREAM_ERROR$1; + } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + +} + +function inflateReset2(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { + return Z_STREAM_ERROR$1; + } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR$1; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); +} + +function inflateInit2(strm, windowBits) { + var ret; + var state; + + if (!strm) { + return Z_STREAM_ERROR$1; + } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null /*Z_NULL*/ ; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK$1) { + strm.state = null /*Z_NULL*/ ; + } + return ret; +} + + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +var virgin = true; + +var lenfix, distfix; // We have no pointers in JS, so keep tables separate + +function fixedtables(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + var sym; + + lenfix = new Buf32(512); + distfix = new Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { + state.lens[sym++] = 8; + } + while (sym < 256) { + state.lens[sym++] = 9; + } + while (sym < 280) { + state.lens[sym++] = 7; + } + while (sym < 288) { + state.lens[sym++] = 8; + } + + inflate_table(LENS$1, state.lens, 0, 288, lenfix, 0, state.work, { + bits: 9 + }); + + /* distance table */ + sym = 0; + while (sym < 32) { + state.lens[sym++] = 5; + } + + inflate_table(DISTS$1, state.lens, 0, 32, distfix, 0, state.work, { + bits: 5 + }); + + /* do this just once */ + virgin = false; + } + + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; +} + + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } else { + state.wnext += dist; + if (state.wnext === state.wsize) { + state.wnext = 0; + } + if (state.whave < state.wsize) { + state.whave += dist; + } + } + } + return 0; +} + +function inflate(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR$1; + } + + state = strm.state; + if (state.mode === TYPE$1) { + state.mode = TYPEDO; + } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK$1; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0 /*crc32(0L, Z_NULL, 0)*/ ; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff) /*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD$1; + break; + } + if ((hold & 0x0f) /*BITS(4)*/ !== Z_DEFLATED$1) { + strm.msg = 'unknown compression method'; + state.mode = BAD$1; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f) /*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD$1; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1 /*adler32(0L, Z_NULL, 0)*/ ; + state.mode = hold & 0x200 ? DICTID : TYPE$1; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED$1) { + strm.msg = 'unknown compression method'; + state.mode = BAD$1; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD$1; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } else if (state.head) { + state.head.extra = null /*Z_NULL*/ ; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { + copy = have; + } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more conveniend processing later + state.head.extra = new Array(state.head.extra_len); + } + arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { + break inf_leave; + } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { + break inf_leave; + } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/ )) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { + break inf_leave; + } + } else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { + break inf_leave; + } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/ )) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { + break inf_leave; + } + } else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD$1; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE$1; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = zswap32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT; + } + strm.adler = state.check = 1 /*adler32(0L, Z_NULL, 0)*/ ; + state.mode = TYPE$1; + /* falls through */ + case TYPE$1: + if (flush === Z_BLOCK$1 || flush === Z_TREES) { + break inf_leave; + } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01) /*BITS(1)*/ ; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03) /*BITS(2)*/ ) { + case 0: + /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: + /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: + /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD$1; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD$1; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES) { + break inf_leave; + } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { + copy = have; + } + if (copy > left) { + copy = left; + } + if (copy === 0) { + break inf_leave; + } + //--- zmemcpy(put, next, copy); --- + arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE$1; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f) /*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f) /*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f) /*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + //#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD$1; + break; + } + //#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07); //BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = { + bits: state.lenbits + }; + ret = inflate_table(CODES$1, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + + if (ret) { + strm.msg = 'invalid code lengths set'; + state.mode = BAD$1; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { + break; + } + //--- PULLBYTE() ---// + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD$1; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03); //BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07); //BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f); //BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD$1; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD$1) { + break; + } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD$1; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = { + bits: state.lenbits + }; + ret = inflate_table(LENS$1, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD$1; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = { + bits: state.distbits + }; + ret = inflate_table(DISTS$1, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD$1; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES) { + break inf_leave; + } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inflate_fast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE$1) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { + break; + } + //--- PULLBYTE() ---// + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1)) /*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { + break; + } + //--- PULLBYTE() ---// + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE$1; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD$1; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) - 1) /*BITS(state.extra)*/ ; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) - 1)]; /*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { + break; + } + //--- PULLBYTE() ---// + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1)) /*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { + break; + } + //--- PULLBYTE() ---// + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD$1; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) - 1) /*BITS(state.extra)*/ ; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD$1; + break; + } + //#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { + break inf_leave; + } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD$1; + break; + } + // (!) This block is disabled in zlib defailts, + // don't enable it for binary compatibility + //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + // Trace((stderr, "inflate.c too far\n")); + // copy -= state.whave; + // if (copy > state.length) { copy = state.length; } + // if (copy > left) { copy = left; } + // left -= copy; + // state.length -= copy; + // do { + // output[put++] = 0; + // } while (--copy); + // if (state.length === 0) { state.mode = LEN; } + // break; + //#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } else { + from = state.wnext - copy; + } + if (copy > state.length) { + copy = state.length; + } + from_source = state.window; + } else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { + copy = left; + } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { + state.mode = LEN; + } + break; + case LIT: + if (left === 0) { + break inf_leave; + } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + // Use '|' insdead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD$1; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD$1; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END$1; + break inf_leave; + case BAD$1: + ret = Z_DATA_ERROR$1; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR$1; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD$1 && + (state.mode < CHECK || flush !== Z_FINISH$1))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ; + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE$1 ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH$1) && ret === Z_OK$1) { + ret = Z_BUF_ERROR$1; + } + return ret; +} + +function inflateEnd(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/ ) { + return Z_STREAM_ERROR$1; + } + + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK$1; +} + +/* Not implemented +exports.inflateCopy = inflateCopy; +exports.inflateGetDictionary = inflateGetDictionary; +exports.inflateMark = inflateMark; +exports.inflatePrime = inflatePrime; +exports.inflateSync = inflateSync; +exports.inflateSyncPoint = inflateSyncPoint; +exports.inflateUndermine = inflateUndermine; +*/ + +// import constants from './constants'; + + +// zlib modes +var NONE = 0; +var DEFLATE = 1; +var INFLATE = 2; +var GZIP = 3; +var GUNZIP = 4; +var DEFLATERAW = 5; +var INFLATERAW = 6; +var UNZIP = 7; +var Z_NO_FLUSH$1= 0, + Z_PARTIAL_FLUSH$1= 1, + Z_SYNC_FLUSH= 2, + Z_FULL_FLUSH$1= 3, + Z_FINISH$2= 4, + Z_BLOCK$2= 5, + Z_TREES$1= 6, + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK$2= 0, + Z_STREAM_END$2= 1, + Z_NEED_DICT$1= 2, + Z_ERRNO= -1, + Z_STREAM_ERROR$2= -2, + Z_DATA_ERROR$2= -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR$2= -5, + //Z_VERSION_ERROR: -6, + + /* compression levels */ + Z_NO_COMPRESSION= 0, + Z_BEST_SPEED= 1, + Z_BEST_COMPRESSION= 9, + Z_DEFAULT_COMPRESSION$1= -1, + + + Z_FILTERED$1= 1, + Z_HUFFMAN_ONLY$1= 2, + Z_RLE$1= 3, + Z_FIXED$2= 4, + Z_DEFAULT_STRATEGY= 0, + + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY$1= 0, + Z_TEXT$1= 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN$2= 2, + + /* The deflate compression method */ + Z_DEFLATED$2= 8; +function Zlib(mode) { + if (mode < DEFLATE || mode > UNZIP) + throw new TypeError('Bad argument'); + + this.mode = mode; + this.init_done = false; + this.write_in_progress = false; + this.pending_close = false; + this.windowBits = 0; + this.level = 0; + this.memLevel = 0; + this.strategy = 0; + this.dictionary = null; +} + +Zlib.prototype.init = function(windowBits, level, memLevel, strategy, dictionary) { + this.windowBits = windowBits; + this.level = level; + this.memLevel = memLevel; + this.strategy = strategy; + // dictionary not supported. + + if (this.mode === GZIP || this.mode === GUNZIP) + this.windowBits += 16; + + if (this.mode === UNZIP) + this.windowBits += 32; + + if (this.mode === DEFLATERAW || this.mode === INFLATERAW) + this.windowBits = -this.windowBits; + + this.strm = new ZStream(); + var status; + switch (this.mode) { + case DEFLATE: + case GZIP: + case DEFLATERAW: + status = deflateInit2( + this.strm, + this.level, + Z_DEFLATED$2, + this.windowBits, + this.memLevel, + this.strategy + ); + break; + case INFLATE: + case GUNZIP: + case INFLATERAW: + case UNZIP: + status = inflateInit2( + this.strm, + this.windowBits + ); + break; + default: + throw new Error('Unknown mode ' + this.mode); + } + + if (status !== Z_OK$2) { + this._error(status); + return; + } + + this.write_in_progress = false; + this.init_done = true; +}; + +Zlib.prototype.params = function() { + throw new Error('deflateParams Not supported'); +}; + +Zlib.prototype._writeCheck = function() { + if (!this.init_done) + throw new Error('write before init'); + + if (this.mode === NONE) + throw new Error('already finalized'); + + if (this.write_in_progress) + throw new Error('write already in progress'); + + if (this.pending_close) + throw new Error('close is pending'); +}; + +Zlib.prototype.write = function(flush, input, in_off, in_len, out, out_off, out_len) { + this._writeCheck(); + this.write_in_progress = true; + + var self = this; + nextTick(function() { + self.write_in_progress = false; + var res = self._write(flush, input, in_off, in_len, out, out_off, out_len); + self.callback(res[0], res[1]); + + if (self.pending_close) + self.close(); + }); + + return this; +}; + +// set method for Node buffers, used by pako +function bufferSet(data, offset) { + for (var i = 0; i < data.length; i++) { + this[offset + i] = data[i]; + } +} + +Zlib.prototype.writeSync = function(flush, input, in_off, in_len, out, out_off, out_len) { + this._writeCheck(); + return this._write(flush, input, in_off, in_len, out, out_off, out_len); +}; + +Zlib.prototype._write = function(flush, input, in_off, in_len, out, out_off, out_len) { + this.write_in_progress = true; + + if (flush !== Z_NO_FLUSH$1 && + flush !== Z_PARTIAL_FLUSH$1 && + flush !== Z_SYNC_FLUSH && + flush !== Z_FULL_FLUSH$1 && + flush !== Z_FINISH$2 && + flush !== Z_BLOCK$2) { + throw new Error('Invalid flush value'); + } + + if (input == null) { + input = new Buffer$1(0); + in_len = 0; + in_off = 0; + } + + if (out._set) + out.set = out._set; + else + out.set = bufferSet; + + var strm = this.strm; + strm.avail_in = in_len; + strm.input = input; + strm.next_in = in_off; + strm.avail_out = out_len; + strm.output = out; + strm.next_out = out_off; + var status; + switch (this.mode) { + case DEFLATE: + case GZIP: + case DEFLATERAW: + status = deflate(strm, flush); + break; + case UNZIP: + case INFLATE: + case GUNZIP: + case INFLATERAW: + status = inflate(strm, flush); + break; + default: + throw new Error('Unknown mode ' + this.mode); + } + + if (status !== Z_STREAM_END$2 && status !== Z_OK$2) { + this._error(status); + } + + this.write_in_progress = false; + return [strm.avail_in, strm.avail_out]; +}; + +Zlib.prototype.close = function() { + if (this.write_in_progress) { + this.pending_close = true; + return; + } + + this.pending_close = false; + + if (this.mode === DEFLATE || this.mode === GZIP || this.mode === DEFLATERAW) { + deflateEnd(this.strm); + } else { + inflateEnd(this.strm); + } + + this.mode = NONE; +}; +var status; +Zlib.prototype.reset = function() { + switch (this.mode) { + case DEFLATE: + case DEFLATERAW: + status = deflateReset(this.strm); + break; + case INFLATE: + case INFLATERAW: + status = inflateReset(this.strm); + break; + } + + if (status !== Z_OK$2) { + this._error(status); + } +}; + +Zlib.prototype._error = function(status) { + this.onerror(msg[status] + ': ' + this.strm.msg, status); + + this.write_in_progress = false; + if (this.pending_close) + this.close(); +}; + +var _binding = /*#__PURE__*/Object.freeze({ + __proto__: null, + NONE: NONE, + DEFLATE: DEFLATE, + INFLATE: INFLATE, + GZIP: GZIP, + GUNZIP: GUNZIP, + DEFLATERAW: DEFLATERAW, + INFLATERAW: INFLATERAW, + UNZIP: UNZIP, + Z_NO_FLUSH: Z_NO_FLUSH$1, + Z_PARTIAL_FLUSH: Z_PARTIAL_FLUSH$1, + Z_SYNC_FLUSH: Z_SYNC_FLUSH, + Z_FULL_FLUSH: Z_FULL_FLUSH$1, + Z_FINISH: Z_FINISH$2, + Z_BLOCK: Z_BLOCK$2, + Z_TREES: Z_TREES$1, + Z_OK: Z_OK$2, + Z_STREAM_END: Z_STREAM_END$2, + Z_NEED_DICT: Z_NEED_DICT$1, + Z_ERRNO: Z_ERRNO, + Z_STREAM_ERROR: Z_STREAM_ERROR$2, + Z_DATA_ERROR: Z_DATA_ERROR$2, + Z_BUF_ERROR: Z_BUF_ERROR$2, + Z_NO_COMPRESSION: Z_NO_COMPRESSION, + Z_BEST_SPEED: Z_BEST_SPEED, + Z_BEST_COMPRESSION: Z_BEST_COMPRESSION, + Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION$1, + Z_FILTERED: Z_FILTERED$1, + Z_HUFFMAN_ONLY: Z_HUFFMAN_ONLY$1, + Z_RLE: Z_RLE$1, + Z_FIXED: Z_FIXED$2, + Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY, + Z_BINARY: Z_BINARY$1, + Z_TEXT: Z_TEXT$1, + Z_UNKNOWN: Z_UNKNOWN$2, + Z_DEFLATED: Z_DEFLATED$2, + Zlib: Zlib +}); + +function assert (a, msg) { + if (!a) { + throw new Error(msg); + } +} +var binding$1 = {}; +Object.keys(_binding).forEach(function (key) { + binding$1[key] = _binding[key]; +}); +// zlib doesn't provide these, so kludge them in following the same +// const naming scheme zlib uses. +binding$1.Z_MIN_WINDOWBITS = 8; +binding$1.Z_MAX_WINDOWBITS = 15; +binding$1.Z_DEFAULT_WINDOWBITS = 15; + +// fewer than 64 bytes per chunk is stupid. +// technically it could work with as few as 8, but even 64 bytes +// is absurdly low. Usually a MB or more is best. +binding$1.Z_MIN_CHUNK = 64; +binding$1.Z_MAX_CHUNK = Infinity; +binding$1.Z_DEFAULT_CHUNK = (16 * 1024); + +binding$1.Z_MIN_MEMLEVEL = 1; +binding$1.Z_MAX_MEMLEVEL = 9; +binding$1.Z_DEFAULT_MEMLEVEL = 8; + +binding$1.Z_MIN_LEVEL = -1; +binding$1.Z_MAX_LEVEL = 9; +binding$1.Z_DEFAULT_LEVEL = binding$1.Z_DEFAULT_COMPRESSION; + + +// translation table for return codes. +var codes = { + Z_OK: binding$1.Z_OK, + Z_STREAM_END: binding$1.Z_STREAM_END, + Z_NEED_DICT: binding$1.Z_NEED_DICT, + Z_ERRNO: binding$1.Z_ERRNO, + Z_STREAM_ERROR: binding$1.Z_STREAM_ERROR, + Z_DATA_ERROR: binding$1.Z_DATA_ERROR, + Z_MEM_ERROR: binding$1.Z_MEM_ERROR, + Z_BUF_ERROR: binding$1.Z_BUF_ERROR, + Z_VERSION_ERROR: binding$1.Z_VERSION_ERROR +}; + +Object.keys(codes).forEach(function(k) { + codes[codes[k]] = k; +}); + +function createDeflate(o) { + return new Deflate(o); +} + +function createInflate(o) { + return new Inflate(o); +} + +function createDeflateRaw(o) { + return new DeflateRaw(o); +} + +function createInflateRaw(o) { + return new InflateRaw(o); +} + +function createGzip(o) { + return new Gzip(o); +} + +function createGunzip(o) { + return new Gunzip(o); +} + +function createUnzip(o) { + return new Unzip(o); +} + + +// Convenience methods. +// compress/decompress a string or buffer in one step. +function deflate$1(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Deflate(opts), buffer, callback); +} + +function deflateSync(buffer, opts) { + return zlibBufferSync(new Deflate(opts), buffer); +} + +function gzip(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Gzip(opts), buffer, callback); +} + +function gzipSync(buffer, opts) { + return zlibBufferSync(new Gzip(opts), buffer); +} + +function deflateRaw(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new DeflateRaw(opts), buffer, callback); +} + +function deflateRawSync(buffer, opts) { + return zlibBufferSync(new DeflateRaw(opts), buffer); +} + +function unzip(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Unzip(opts), buffer, callback); +} + +function unzipSync(buffer, opts) { + return zlibBufferSync(new Unzip(opts), buffer); +} + +function inflate$1(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Inflate(opts), buffer, callback); +} + +function inflateSync(buffer, opts) { + return zlibBufferSync(new Inflate(opts), buffer); +} + +function gunzip(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Gunzip(opts), buffer, callback); +} + +function gunzipSync(buffer, opts) { + return zlibBufferSync(new Gunzip(opts), buffer); +} + +function inflateRaw(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new InflateRaw(opts), buffer, callback); +} + +function inflateRawSync(buffer, opts) { + return zlibBufferSync(new InflateRaw(opts), buffer); +} + +function zlibBuffer(engine, buffer, callback) { + var buffers = []; + var nread = 0; + + engine.on('error', onError); + engine.on('end', onEnd); + + engine.end(buffer); + flow(); + + function flow() { + var chunk; + while (null !== (chunk = engine.read())) { + buffers.push(chunk); + nread += chunk.length; + } + engine.once('readable', flow); + } + + function onError(err) { + engine.removeListener('end', onEnd); + engine.removeListener('readable', flow); + callback(err); + } + + function onEnd() { + var buf = Buffer$1.concat(buffers, nread); + buffers = []; + callback(null, buf); + engine.close(); + } +} + +function zlibBufferSync(engine, buffer) { + if (typeof buffer === 'string') + buffer = new Buffer$1(buffer); + if (!isBuffer(buffer)) + throw new TypeError('Not a string or buffer'); + + var flushFlag = binding$1.Z_FINISH; + + return engine._processChunk(buffer, flushFlag); +} + +// generic zlib +// minimal 2-byte header +function Deflate(opts) { + if (!(this instanceof Deflate)) return new Deflate(opts); + Zlib$1.call(this, opts, binding$1.DEFLATE); +} + +function Inflate(opts) { + if (!(this instanceof Inflate)) return new Inflate(opts); + Zlib$1.call(this, opts, binding$1.INFLATE); +} + + + +// gzip - bigger header, same deflate compression +function Gzip(opts) { + if (!(this instanceof Gzip)) return new Gzip(opts); + Zlib$1.call(this, opts, binding$1.GZIP); +} + +function Gunzip(opts) { + if (!(this instanceof Gunzip)) return new Gunzip(opts); + Zlib$1.call(this, opts, binding$1.GUNZIP); +} + + + +// raw - no header +function DeflateRaw(opts) { + if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts); + Zlib$1.call(this, opts, binding$1.DEFLATERAW); +} + +function InflateRaw(opts) { + if (!(this instanceof InflateRaw)) return new InflateRaw(opts); + Zlib$1.call(this, opts, binding$1.INFLATERAW); +} + + +// auto-detect header. +function Unzip(opts) { + if (!(this instanceof Unzip)) return new Unzip(opts); + Zlib$1.call(this, opts, binding$1.UNZIP); +} + + +// the Zlib class they all inherit from +// This thing manages the queue of requests, and returns +// true or false if there is anything in the queue when +// you call the .write() method. + +function Zlib$1(opts, mode) { + this._opts = opts = opts || {}; + this._chunkSize = opts.chunkSize || binding$1.Z_DEFAULT_CHUNK; + + Transform.call(this, opts); + + if (opts.flush) { + if (opts.flush !== binding$1.Z_NO_FLUSH && + opts.flush !== binding$1.Z_PARTIAL_FLUSH && + opts.flush !== binding$1.Z_SYNC_FLUSH && + opts.flush !== binding$1.Z_FULL_FLUSH && + opts.flush !== binding$1.Z_FINISH && + opts.flush !== binding$1.Z_BLOCK) { + throw new Error('Invalid flush flag: ' + opts.flush); + } + } + this._flushFlag = opts.flush || binding$1.Z_NO_FLUSH; + + if (opts.chunkSize) { + if (opts.chunkSize < binding$1.Z_MIN_CHUNK || + opts.chunkSize > binding$1.Z_MAX_CHUNK) { + throw new Error('Invalid chunk size: ' + opts.chunkSize); + } + } + + if (opts.windowBits) { + if (opts.windowBits < binding$1.Z_MIN_WINDOWBITS || + opts.windowBits > binding$1.Z_MAX_WINDOWBITS) { + throw new Error('Invalid windowBits: ' + opts.windowBits); + } + } + + if (opts.level) { + if (opts.level < binding$1.Z_MIN_LEVEL || + opts.level > binding$1.Z_MAX_LEVEL) { + throw new Error('Invalid compression level: ' + opts.level); + } + } + + if (opts.memLevel) { + if (opts.memLevel < binding$1.Z_MIN_MEMLEVEL || + opts.memLevel > binding$1.Z_MAX_MEMLEVEL) { + throw new Error('Invalid memLevel: ' + opts.memLevel); + } + } + + if (opts.strategy) { + if (opts.strategy != binding$1.Z_FILTERED && + opts.strategy != binding$1.Z_HUFFMAN_ONLY && + opts.strategy != binding$1.Z_RLE && + opts.strategy != binding$1.Z_FIXED && + opts.strategy != binding$1.Z_DEFAULT_STRATEGY) { + throw new Error('Invalid strategy: ' + opts.strategy); + } + } + + if (opts.dictionary) { + if (!isBuffer(opts.dictionary)) { + throw new Error('Invalid dictionary: it should be a Buffer instance'); + } + } + + this._binding = new binding$1.Zlib(mode); + + var self = this; + this._hadError = false; + this._binding.onerror = function(message, errno) { + // there is no way to cleanly recover. + // continuing only obscures problems. + self._binding = null; + self._hadError = true; + + var error = new Error(message); + error.errno = errno; + error.code = binding$1.codes[errno]; + self.emit('error', error); + }; + + var level = binding$1.Z_DEFAULT_COMPRESSION; + if (typeof opts.level === 'number') level = opts.level; + + var strategy = binding$1.Z_DEFAULT_STRATEGY; + if (typeof opts.strategy === 'number') strategy = opts.strategy; + + this._binding.init(opts.windowBits || binding$1.Z_DEFAULT_WINDOWBITS, + level, + opts.memLevel || binding$1.Z_DEFAULT_MEMLEVEL, + strategy, + opts.dictionary); + + this._buffer = new Buffer$1(this._chunkSize); + this._offset = 0; + this._closed = false; + this._level = level; + this._strategy = strategy; + + this.once('end', this.close); +} + +inherits$1(Zlib$1, Transform); + +Zlib$1.prototype.params = function(level, strategy, callback) { + if (level < binding$1.Z_MIN_LEVEL || + level > binding$1.Z_MAX_LEVEL) { + throw new RangeError('Invalid compression level: ' + level); + } + if (strategy != binding$1.Z_FILTERED && + strategy != binding$1.Z_HUFFMAN_ONLY && + strategy != binding$1.Z_RLE && + strategy != binding$1.Z_FIXED && + strategy != binding$1.Z_DEFAULT_STRATEGY) { + throw new TypeError('Invalid strategy: ' + strategy); + } + + if (this._level !== level || this._strategy !== strategy) { + var self = this; + this.flush(binding$1.Z_SYNC_FLUSH, function() { + self._binding.params(level, strategy); + if (!self._hadError) { + self._level = level; + self._strategy = strategy; + if (callback) callback(); + } + }); + } else { + nextTick(callback); + } +}; + +Zlib$1.prototype.reset = function() { + return this._binding.reset(); +}; + +// This is the _flush function called by the transform class, +// internally, when the last chunk has been written. +Zlib$1.prototype._flush = function(callback) { + this._transform(new Buffer$1(0), '', callback); +}; + +Zlib$1.prototype.flush = function(kind, callback) { + var ws = this._writableState; + + if (typeof kind === 'function' || (kind === void 0 && !callback)) { + callback = kind; + kind = binding$1.Z_FULL_FLUSH; + } + + if (ws.ended) { + if (callback) + nextTick(callback); + } else if (ws.ending) { + if (callback) + this.once('end', callback); + } else if (ws.needDrain) { + var self = this; + this.once('drain', function() { + self.flush(callback); + }); + } else { + this._flushFlag = kind; + this.write(new Buffer$1(0), '', callback); + } +}; + +Zlib$1.prototype.close = function(callback) { + if (callback) + nextTick(callback); + + if (this._closed) + return; + + this._closed = true; + + this._binding.close(); + + var self = this; + nextTick(function() { + self.emit('close'); + }); +}; + +Zlib$1.prototype._transform = function(chunk, encoding, cb) { + var flushFlag; + var ws = this._writableState; + var ending = ws.ending || ws.ended; + var last = ending && (!chunk || ws.length === chunk.length); + + if (!chunk === null && !isBuffer(chunk)) + return cb(new Error('invalid input')); + + // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag. + // If it's explicitly flushing at some other time, then we use + // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression + // goodness. + if (last) + flushFlag = binding$1.Z_FINISH; + else { + flushFlag = this._flushFlag; + // once we've flushed the last of the queue, stop flushing and + // go back to the normal behavior. + if (chunk.length >= ws.length) { + this._flushFlag = this._opts.flush || binding$1.Z_NO_FLUSH; + } + } + + this._processChunk(chunk, flushFlag, cb); +}; + +Zlib$1.prototype._processChunk = function(chunk, flushFlag, cb) { + var availInBefore = chunk && chunk.length; + var availOutBefore = this._chunkSize - this._offset; + var inOff = 0; + + var self = this; + + var async = typeof cb === 'function'; + + if (!async) { + var buffers = []; + var nread = 0; + + var error; + this.on('error', function(er) { + error = er; + }); + + do { + var res = this._binding.writeSync(flushFlag, + chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore); // out_len + } while (!this._hadError && callback(res[0], res[1])); + + if (this._hadError) { + throw error; + } + + var buf = Buffer$1.concat(buffers, nread); + this.close(); + + return buf; + } + + var req = this._binding.write(flushFlag, + chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore); // out_len + + req.buffer = chunk; + req.callback = callback; + + function callback(availInAfter, availOutAfter) { + if (self._hadError) + return; + + var have = availOutBefore - availOutAfter; + assert(have >= 0, 'have should not go down'); + + if (have > 0) { + var out = self._buffer.slice(self._offset, self._offset + have); + self._offset += have; + // serve some output to the consumer. + if (async) { + self.push(out); + } else { + buffers.push(out); + nread += out.length; + } + } + + // exhausted the output buffer, or used all the input create a new one. + if (availOutAfter === 0 || self._offset >= self._chunkSize) { + availOutBefore = self._chunkSize; + self._offset = 0; + self._buffer = new Buffer$1(self._chunkSize); + } + + if (availOutAfter === 0) { + // Not actually done. Need to reprocess. + // Also, update the availInBefore to the availInAfter value, + // so that if we have to hit it a third (fourth, etc.) time, + // it'll have the correct byte counts. + inOff += (availInBefore - availInAfter); + availInBefore = availInAfter; + + if (!async) + return true; + + var newReq = self._binding.write(flushFlag, + chunk, + inOff, + availInBefore, + self._buffer, + self._offset, + self._chunkSize); + newReq.callback = callback; // this same function + newReq.buffer = chunk; + return; + } + + if (!async) + return false; + + // finished with the chunk. + cb(); + } +}; + +inherits$1(Deflate, Zlib$1); +inherits$1(Inflate, Zlib$1); +inherits$1(Gzip, Zlib$1); +inherits$1(Gunzip, Zlib$1); +inherits$1(DeflateRaw, Zlib$1); +inherits$1(InflateRaw, Zlib$1); +inherits$1(Unzip, Zlib$1); +var zlib = { + codes: codes, + createDeflate: createDeflate, + createInflate: createInflate, + createDeflateRaw: createDeflateRaw, + createInflateRaw: createInflateRaw, + createGzip: createGzip, + createGunzip: createGunzip, + createUnzip: createUnzip, + deflate: deflate$1, + deflateSync: deflateSync, + gzip: gzip, + gzipSync: gzipSync, + deflateRaw: deflateRaw, + deflateRawSync: deflateRawSync, + unzip: unzip, + unzipSync: unzipSync, + inflate: inflate$1, + inflateSync: inflateSync, + gunzip: gunzip, + gunzipSync: gunzipSync, + inflateRaw: inflateRaw, + inflateRawSync: inflateRawSync, + Deflate: Deflate, + Inflate: Inflate, + Gzip: Gzip, + Gunzip: Gunzip, + DeflateRaw: DeflateRaw, + InflateRaw: InflateRaw, + Unzip: Unzip, + Zlib: Zlib$1 +}; + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable$1 = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE$2 = Symbol('type'); + +class Blob { + constructor() { + this[TYPE$2] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE$2] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE$2]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable$1(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES$1 = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES$1[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parse_url(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parse_url(`${input}`); + } + input = {}; + } else { + parsedURL = parse_url(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + if (!headers.has('Connection') && !agent) { + headers.set('Connection', 'close'); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1$1 = Stream.PassThrough; +const resolve_url = Url.resolve; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? http : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + request.body.destroy(error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + finalize(); + }); + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + const locationURL = location === null ? null : resolve_url(request.url, location); + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +var lib = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': fetch, + Headers: Headers, + Request: Request, + Response: Response, + FetchError: FetchError +}); + +var browser$1 = true; + +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +var ms = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse$2(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse$2(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = ms; + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; +} + +var common = setup; + +var browser$2 = createCommonjsModule(function (module, exports) { +/* eslint-env browser */ + +/** + * This is the web browser implementation of `debug()`. + */ + +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); + +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ +exports.log = console.debug || console.log || (() => {}); + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +module.exports = common(exports); + +const {formatters} = module.exports; + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; +}); +var browser_1 = browser$2.formatArgs; +var browser_2 = browser$2.save; +var browser_3 = browser$2.load; +var browser_4 = browser$2.useColors; +var browser_5 = browser$2.storage; +var browser_6 = browser$2.destroy; +var browser_7 = browser$2.colors; +var browser_8 = browser$2.log; + +// MIT lisence +// from https://github.com/substack/tty-browserify/blob/1ba769a6429d242f36226538835b4034bf6b7886/index.js + +function isatty() { + return false; +} + +function ReadStream() { + throw new Error('tty.ReadStream is not implemented'); +} + +function WriteStream() { + throw new Error('tty.ReadStream is not implemented'); +} + +var tty = { + isatty: isatty, + ReadStream: ReadStream, + WriteStream: WriteStream +}; + +var hasFlag = (flag, argv) => { + argv = argv || process.argv; + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const pos = argv.indexOf(prefix + flag); + const terminatorPos = argv.indexOf('--'); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); +}; + +const env$1 = process.env; + +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = true; +} +if ('FORCE_COLOR' in env$1) { + forceColor = env$1.FORCE_COLOR.length === 0 || parseInt(env$1.FORCE_COLOR, 10) !== 0; +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } + + const min = forceColor ? 1 : 0; + + if ('CI' in env$1) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env$1) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env$1.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env$1) { + const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env$1.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env$1.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) { + return 1; + } + + if ('COLORTERM' in env$1) { + return 1; + } + + if (env$1.TERM === 'dumb') { + return min; + } + + return min; +} + +function getSupportLevel(stream) { + const level = supportsColor(stream); + return translateLevel(level); +} + +var supportsColor_1 = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) +}; + +var node = createCommonjsModule(function (module, exports) { +/** + * Module dependencies. + */ + + + + +/** + * This is the Node.js implementation of `debug()`. + */ + +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = supportsColor_1; + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. +} + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; +}, {}); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} + +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init(debug) { + debug.inspectOpts = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +module.exports = common(exports); + +const {formatters} = module.exports; + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; + +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; +}); +var node_1 = node.init; +var node_2 = node.log; +var node_3 = node.formatArgs; +var node_4 = node.save; +var node_5 = node.load; +var node_6 = node.useColors; +var node_7 = node.destroy; +var node_8 = node.colors; +var node_9 = node.inspectOpts; + +var src = createCommonjsModule(function (module) { +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer' || browser$1 === true || process.__nwjs) { + module.exports = browser$2; +} else { + module.exports = node; +} +}); + +let debugFunc; +let phase = 'default'; +let namespace = ''; +const newDebug = () => { + debugFunc = namespace + ? src(`fetch-mock:${phase}:${namespace}`) + : src(`fetch-mock:${phase}`); +}; + +const newDebugSandbox = (ns) => src(`fetch-mock:${phase}:${ns}`); + +newDebug(); + +var debug_1 = { + debug: (...args) => { + debugFunc(...args); + }, + setDebugNamespace: (str) => { + namespace = str; + newDebug(); + }, + setDebugPhase: (str) => { + phase = str || 'default'; + newDebug(); + }, + getDebug: (namespace) => newDebugSandbox(namespace), +}; + +const { debug: debug$1, setDebugPhase } = debug_1; +const FetchMock = {}; + +FetchMock.mock = function (...args) { + setDebugPhase('setup'); + if (args.length) { + this.addRoute(args); + } + + return this._mock(); +}; + +FetchMock.addRoute = function (uncompiledRoute) { + debug$1('Adding route', uncompiledRoute); + const route = this.compileRoute(uncompiledRoute); + const clashes = this.routes.filter(({ identifier, method }) => { + const isMatch = + typeof identifier === 'function' + ? identifier === route.identifier + : String(identifier) === String(route.identifier); + return isMatch && (!method || !route.method || method === route.method); + }); + + if (this.getOption('overwriteRoutes', route) === false || !clashes.length) { + this._uncompiledRoutes.push(uncompiledRoute); + return this.routes.push(route); + } + + if (this.getOption('overwriteRoutes', route) === true) { + clashes.forEach((clash) => { + const index = this.routes.indexOf(clash); + this._uncompiledRoutes.splice(index, 1, uncompiledRoute); + this.routes.splice(index, 1, route); + }); + return this.routes; + } + + if (clashes.length) { + throw new Error( + 'fetch-mock: Adding route with same name or matcher as existing route. See `overwriteRoutes` option.' + ); + } + + this._uncompiledRoutes.push(uncompiledRoute); + this.routes.push(route); +}; + +FetchMock._mock = function () { + if (!this.isSandbox) { + // Do this here rather than in the constructor to ensure it's scoped to the test + this.realFetch = this.realFetch || this.global.fetch; + this.global.fetch = this.fetchHandler; + } + setDebugPhase(); + return this; +}; + +FetchMock.catch = function (response) { + if (this.fallbackResponse) { + console.warn( + 'calling fetchMock.catch() twice - are you sure you want to overwrite the previous fallback response' + ); // eslint-disable-line + } + this.fallbackResponse = response || 'ok'; + return this._mock(); +}; + +FetchMock.spy = function (route) { + // even though ._mock() is called by .mock() and .catch() we still need to + // call it here otherwise .getNativeFetch() won't be able to use the reference + // to .realFetch that ._mock() sets up + this._mock(); + return route + ? this.mock(route, this.getNativeFetch()) + : this.catch(this.getNativeFetch()); +}; + +const defineShorthand = (methodName, underlyingMethod, shorthandOptions) => { + FetchMock[methodName] = function (matcher, response, options) { + return this[underlyingMethod]( + matcher, + response, + Object.assign(options || {}, shorthandOptions) + ); + }; +}; + +const defineGreedyShorthand = (methodName, underlyingMethod) => { + FetchMock[methodName] = function (response, options) { + return this[underlyingMethod]({}, response, options); + }; +}; + +defineShorthand('sticky', 'mock', { sticky: true }); +defineShorthand('once', 'mock', { repeat: 1 }); +defineGreedyShorthand('any', 'mock'); +defineGreedyShorthand('anyOnce', 'once'); + +['get', 'post', 'put', 'delete', 'head', 'patch'].forEach((method) => { + defineShorthand(method, 'mock', { method }); + defineShorthand(`${method}Once`, 'once', { method }); + defineGreedyShorthand(`${method}Any`, method); + defineGreedyShorthand(`${method}AnyOnce`, `${method}Once`); +}); + +const mochaAsyncHookWorkaround = (options) => { + // HACK workaround for this https://github.com/mochajs/mocha/issues/4280 + // Note that it doesn't matter that we call it _before_ carrying out all + // the things resetBehavior does as everything in there is synchronous + if (typeof options === 'function') { + console.warn(`Deprecated: Passing fetch-mock reset methods +directly in as handlers for before/after test runner hooks. +Wrap in an arrow function instead e.g. \`() => fetchMock.restore()\``); + options(); + } +}; + +const getRouteRemover = ({ sticky: removeStickyRoutes }) => (routes) => + removeStickyRoutes ? [] : routes.filter(({ sticky }) => sticky); + +FetchMock.resetBehavior = function (options = {}) { + mochaAsyncHookWorkaround(options); + const removeRoutes = getRouteRemover(options); + + this.routes = removeRoutes(this.routes); + this._uncompiledRoutes = removeRoutes(this._uncompiledRoutes); + + if (this.realFetch && !this.routes.length) { + this.global.fetch = this.realFetch; + this.realFetch = undefined; + } + + this.fallbackResponse = undefined; + return this; +}; + +FetchMock.resetHistory = function () { + this._calls = []; + this._holdingPromises = []; + this.routes.forEach((route) => route.reset && route.reset()); + return this; +}; + +FetchMock.restore = FetchMock.reset = function (options) { + this.resetBehavior(options); + this.resetHistory(); + return this; +}; + +var setUpAndTearDown = FetchMock; + +const { getDebug } = debug_1; +const responseConfigProps = [ + 'body', + 'headers', + 'throws', + 'status', + 'redirectUrl', +]; + +class ResponseBuilder { + constructor(options) { + this.debug = getDebug('ResponseBuilder()'); + this.debug('Response builder created with options', options); + Object.assign(this, options); + } + + exec() { + this.debug('building response'); + this.normalizeResponseConfig(); + this.constructFetchOpts(); + this.constructResponseBody(); + + const realResponse = new this.fetchMock.config.Response( + this.body, + this.options + ); + const proxyResponse = this.buildObservableResponse(realResponse); + return [realResponse, proxyResponse]; + } + + sendAsObject() { + if (responseConfigProps.some((prop) => this.responseConfig[prop])) { + if ( + Object.keys(this.responseConfig).every((key) => + responseConfigProps.includes(key) + ) + ) { + return false; + } else { + return true; + } + } else { + return true; + } + } + + normalizeResponseConfig() { + // If the response config looks like a status, start to generate a simple response + if (typeof this.responseConfig === 'number') { + this.debug('building response using status', this.responseConfig); + this.responseConfig = { + status: this.responseConfig, + }; + // If the response config is not an object, or is an object that doesn't use + // any reserved properties, assume it is meant to be the body of the response + } else if (typeof this.responseConfig === 'string' || this.sendAsObject()) { + this.debug('building text response from', this.responseConfig); + this.responseConfig = { + body: this.responseConfig, + }; + } + } + + validateStatus(status) { + if (!status) { + this.debug('No status provided. Defaulting to 200'); + return 200; + } + + if ( + (typeof status === 'number' && + parseInt(status, 10) !== status && + status >= 200) || + status < 600 + ) { + this.debug('Valid status provided', status); + return status; + } + + throw new TypeError(`fetch-mock: Invalid status ${status} passed on response object. +To respond with a JSON object that has status as a property assign the object to body +e.g. {"body": {"status: "registered"}}`); + } + + constructFetchOpts() { + this.options = this.responseConfig.options || {}; + this.options.url = this.responseConfig.redirectUrl || this.url; + this.options.status = this.validateStatus(this.responseConfig.status); + this.options.statusText = this.fetchMock.statusTextMap[ + String(this.options.status) + ]; + + // Set up response headers. The empty object is to cope with + // new Headers(undefined) throwing in Chrome + // https://code.google.com/p/chromium/issues/detail?id=335871 + this.options.headers = new this.fetchMock.config.Headers( + this.responseConfig.headers || {} + ); + } + + getOption(name) { + return this.fetchMock.getOption(name, this.route); + } + + convertToJson() { + // convert to json if we need to + if ( + this.getOption('sendAsJson') && + this.responseConfig.body != null && //eslint-disable-line + typeof this.body === 'object' + ) { + this.debug('Stringifying JSON response body'); + this.body = JSON.stringify(this.body); + if (!this.options.headers.has('Content-Type')) { + this.options.headers.set('Content-Type', 'application/json'); + } + } + } + + setContentLength() { + // add a Content-Length header if we need to + if ( + this.getOption('includeContentLength') && + typeof this.body === 'string' && + !this.options.headers.has('Content-Length') + ) { + this.debug('Setting content-length header:', this.body.length.toString()); + this.options.headers.set('Content-Length', this.body.length.toString()); + } + } + + constructResponseBody() { + // start to construct the body + this.body = this.responseConfig.body; + this.convertToJson(); + this.setContentLength(); + + // On the server we need to manually construct the readable stream for the + // Response object (on the client this done automatically) + if (this.Stream) { + this.debug('Creating response stream'); + const stream = new this.Stream.Readable(); + if (this.body != null) { //eslint-disable-line + stream.push(this.body, 'utf-8'); + } + stream.push(null); + this.body = stream; + } + this.body = this.body; + } + + buildObservableResponse(response) { + const fetchMock = this.fetchMock; + response._fmResults = {}; + // Using a proxy means we can set properties that may not be writable on + // the original Response. It also means we can track the resolution of + // promises returned by res.json(), res.text() etc + this.debug('Wrapping Response in ES proxy for observability'); + return new Proxy(response, { + get: (originalResponse, name) => { + if (this.responseConfig.redirectUrl) { + if (name === 'url') { + this.debug( + 'Retrieving redirect url', + this.responseConfig.redirectUrl + ); + return this.responseConfig.redirectUrl; + } + + if (name === 'redirected') { + this.debug('Retrieving redirected status', true); + return true; + } + } + + if (typeof originalResponse[name] === 'function') { + this.debug('Wrapping body promises in ES proxies for observability'); + return new Proxy(originalResponse[name], { + apply: (func, thisArg, args) => { + this.debug(`Calling res.${name}`); + const result = func.apply(response, args); + if (result.then) { + fetchMock._holdingPromises.push(result.catch(() => null)); + originalResponse._fmResults[name] = result; + } + return result; + }, + }); + } + + return originalResponse[name]; + }, + }); + } +} + +var responseBuilder = (options) => new ResponseBuilder(options).exec(); + +let URL; +// https://stackoverflow.com/a/19709846/308237 +// split, URL constructor does not support protocol-relative urls +const absoluteUrlRX = new RegExp('^[a-z]+://', 'i'); +const protocolRelativeUrlRX = new RegExp('^//', 'i'); + +const headersToArray = (headers) => { + // node-fetch 1 Headers + if (typeof headers.raw === 'function') { + return Object.entries(headers.raw()); + } else if (headers[Symbol.iterator]) { + return [...headers]; + } else { + return Object.entries(headers); + } +}; + +const zipObject = (entries) => + entries.reduce((obj, [key, val]) => Object.assign(obj, { [key]: val }), {}); + +const normalizeUrl = (url) => { + if ( + typeof url === 'function' || + url instanceof RegExp || + /^(begin|end|glob|express|path)\:/.test(url) + ) { + return url; + } + if (absoluteUrlRX.test(url)) { + const u = new URL(url); + return u.href; + } else if (protocolRelativeUrlRX.test(url)) { + const u = new URL(url, 'http://dummy'); + return u.href; + } else { + const u = new URL(url, 'http://dummy'); + return u.pathname + u.search; + } +}; + +const extractBody = async (request) => { + try { + // node-fetch + if ('body' in request) { + return request.body.toString(); + } + // fetch + return request.clone().text(); + } catch (err) {} +}; + +var requestUtils = { + setUrlImplementation: (it) => { + URL = it; + }, + normalizeRequest: (url, options, Request) => { + if (Request.prototype.isPrototypeOf(url)) { + const derivedOptions = { + method: url.method, + }; + + const body = extractBody(url); + + if (typeof body !== 'undefined') { + derivedOptions.body = body; + } + + const normalizedRequestObject = { + url: normalizeUrl(url.url), + options: Object.assign(derivedOptions, options), + request: url, + signal: (options && options.signal) || url.signal, + }; + + const headers = headersToArray(url.headers); + + if (headers.length) { + normalizedRequestObject.options.headers = zipObject(headers); + } + return normalizedRequestObject; + } else if ( + typeof url === 'string' || + // horrible URL object duck-typing + (typeof url === 'object' && 'href' in url) + ) { + return { + url: normalizeUrl(url), + options: options, + signal: options && options.signal, + }; + } else if (typeof url === 'object') { + throw new TypeError( + 'fetch-mock: Unrecognised Request object. Read the Config and Installation sections of the docs' + ); + } else { + throw new TypeError('fetch-mock: Invalid arguments passed to fetch'); + } + }, + normalizeUrl, + getPath: (url) => { + const u = absoluteUrlRX.test(url) + ? new URL(url) + : new URL(url, 'http://dummy'); + return u.pathname; + }, + + getQuery: (url) => { + const u = absoluteUrlRX.test(url) + ? new URL(url) + : new URL(url, 'http://dummy'); + return u.search ? u.search.substr(1) : ''; + }, + headers: { + normalize: (headers) => zipObject(headersToArray(headers)), + toLowerCase: (headers) => + Object.keys(headers).reduce((obj, k) => { + obj[k.toLowerCase()] = headers[k]; + return obj; + }, {}), + equal: (actualHeader, expectedHeader) => { + actualHeader = Array.isArray(actualHeader) + ? actualHeader + : [actualHeader]; + expectedHeader = Array.isArray(expectedHeader) + ? expectedHeader + : [expectedHeader]; + + if (actualHeader.length !== expectedHeader.length) { + return false; + } + + return actualHeader.every((val, i) => val === expectedHeader[i]); + }, + }, +}; + +const { debug: debug$2, setDebugPhase: setDebugPhase$1, getDebug: getDebug$1 } = debug_1; + + +const FetchMock$1 = {}; + +// see https://heycam.github.io/webidl/#aborterror for the standardised interface +// Note that this differs slightly from node-fetch +class AbortError$1 extends Error { + constructor() { + super(...arguments); + this.name = 'AbortError'; + this.message = 'The operation was aborted.'; + + // Do not include this class in the stacktrace + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } +} + +// Patch native fetch to avoid "NotSupportedError:ReadableStream uploading is not supported" in Safari. +// See also https://github.com/wheresrhys/fetch-mock/issues/584 +// See also https://stackoverflow.com/a/50952018/1273406 +const patchNativeFetchForSafari = (nativeFetch) => { + // Try to patch fetch only on Safari + if ( + typeof navigator === 'undefined' || + !navigator.vendor || + navigator.vendor !== 'Apple Computer, Inc.' + ) { + return nativeFetch; + } + // It seems the code is working on Safari thus patch native fetch to avoid the error. + return async (request) => { + const { method } = request; + if (!['POST', 'PUT', 'PATCH'].includes(method)) { + // No patch is required in this case + return nativeFetch(request); + } + const body = await request.clone().text(); + const { + cache, + credentials, + headers, + integrity, + mode, + redirect, + referrer, + } = request; + const init = { + body, + cache, + credentials, + headers, + integrity, + mode, + redirect, + referrer, + method, + }; + return nativeFetch(request.url, init); + }; +}; + +const resolve = async ( + { response, responseIsFetch = false }, + url, + options, + request +) => { + const debug = getDebug$1('resolve()'); + debug('Recursively resolving function and promise responses'); + // We want to allow things like + // - function returning a Promise for a response + // - delaying (using a timeout Promise) a function's execution to generate + // a response + // Because of this we can't safely check for function before Promisey-ness, + // or vice versa. So to keep it DRY, and flexible, we keep trying until we + // have something that looks like neither Promise nor function + while (true) { + if (typeof response === 'function') { + debug(' Response is a function'); + // in the case of falling back to the network we need to make sure we're using + // the original Request instance, not our normalised url + options + if (responseIsFetch) { + if (request) { + debug(' -> Calling fetch with Request instance'); + return response(request); + } + debug(' -> Calling fetch with url and options'); + return response(url, options); + } else { + debug(' -> Calling response function'); + response = response(url, options, request); + } + } else if (typeof response.then === 'function') { + debug(' Response is a promise'); + debug(' -> Resolving promise'); + response = await response; + } else { + debug(' Response is not a function or a promise'); + debug(' -> Exiting response resolution recursion'); + return response; + } + } +}; + +FetchMock$1.needsAsyncBodyExtraction = function ({ request }) { + return request && this.routes.some(({ usesBody }) => usesBody); +}; + +FetchMock$1.fetchHandler = function (url, options) { + setDebugPhase$1('handle'); + const debug = getDebug$1('fetchHandler()'); + debug('fetch called with:', url, options); + + const normalizedRequest = requestUtils.normalizeRequest( + url, + options, + this.config.Request + ); + + debug('Request normalised'); + debug(' url', normalizedRequest.url); + debug(' options', normalizedRequest.options); + debug(' request', normalizedRequest.request); + debug(' signal', normalizedRequest.signal); + + if (this.needsAsyncBodyExtraction(normalizedRequest)) { + debug( + 'Need to wait for Body to be streamed before calling router: switching to async mode' + ); + return this._extractBodyThenHandle(normalizedRequest); + } + return this._fetchHandler(normalizedRequest); +}; + +FetchMock$1._extractBodyThenHandle = async function (normalizedRequest) { + normalizedRequest.options.body = await normalizedRequest.options.body; + return this._fetchHandler(normalizedRequest); +}; + +FetchMock$1._fetchHandler = function ({ url, options, request, signal }) { + const { route, callLog } = this.executeRouter(url, options, request); + + this.recordCall(callLog); + + // this is used to power the .flush() method + let done; + this._holdingPromises.push(new this.config.Promise((res) => (done = res))); + + // wrapped in this promise to make sure we respect custom Promise + // constructors defined by the user + return new this.config.Promise((res, rej) => { + if (signal) { + debug$2('signal exists - enabling fetch abort'); + const abort = () => { + debug$2('aborting fetch'); + // note that DOMException is not available in node.js; + // even node-fetch uses a custom error class: + // https://github.com/bitinn/node-fetch/blob/master/src/abort-error.js + rej( + typeof DOMException !== 'undefined' + ? new DOMException('The operation was aborted.', 'AbortError') + : new AbortError$1() + ); + done(); + }; + if (signal.aborted) { + debug$2('signal is already aborted - aborting the fetch'); + abort(); + } + signal.addEventListener('abort', abort); + } + + this.generateResponse({ route, url, options, request, callLog }) + .then(res, rej) + .then(done, done) + .then(() => { + setDebugPhase$1(); + }); + }); +}; + +FetchMock$1.fetchHandler.isMock = true; + +FetchMock$1.executeRouter = function (url, options, request) { + const debug = getDebug$1('executeRouter()'); + const callLog = { url, options, request, isUnmatched: true }; + debug(`Attempting to match request to a route`); + if (this.getOption('fallbackToNetwork') === 'always') { + debug( + ' Configured with fallbackToNetwork=always - passing through to fetch' + ); + return { + route: { response: this.getNativeFetch(), responseIsFetch: true }, + // BUG - this callLog never used to get sent. Discovered the bug + // but can't fix outside a major release as it will potentially + // cause too much disruption + // + // callLog, + }; + } + + const route = this.router(url, options, request); + + if (route) { + debug(' Matching route found'); + return { + route, + callLog: { + url, + options, + request, + identifier: route.identifier, + }, + }; + } + + if (this.getOption('warnOnFallback')) { + console.warn(`Unmatched ${(options && options.method) || 'GET'} to ${url}`); // eslint-disable-line + } + + if (this.fallbackResponse) { + debug(' No matching route found - using fallbackResponse'); + return { route: { response: this.fallbackResponse }, callLog }; + } + + if (!this.getOption('fallbackToNetwork')) { + throw new Error( + `fetch-mock: No fallback response defined for ${ + (options && options.method) || 'GET' + } to ${url}` + ); + } + + debug(' Configured to fallbackToNetwork - passing through to fetch'); + return { + route: { response: this.getNativeFetch(), responseIsFetch: true }, + callLog, + }; +}; + +FetchMock$1.generateResponse = async function ({ + route, + url, + options, + request, + callLog = {}, +}) { + const debug = getDebug$1('generateResponse()'); + const response = await resolve(route, url, options, request); + + // If the response says to throw an error, throw it + // Type checking is to deal with sinon spies having a throws property :-0 + if (response.throws && typeof response !== 'function') { + debug('response.throws is defined - throwing an error'); + throw response.throws; + } + + // If the response is a pre-made Response, respond with it + if (this.config.Response.prototype.isPrototypeOf(response)) { + debug('response is already a Response instance - returning it'); + callLog.response = response; + return response; + } + + // finally, if we need to convert config into a response, we do it + const [realResponse, finalResponse] = responseBuilder({ + url, + responseConfig: response, + fetchMock: this, + route, + }); + + callLog.response = realResponse; + + return finalResponse; +}; + +FetchMock$1.router = function (url, options, request) { + const route = this.routes.find((route, i) => { + debug$2(`Trying to match route ${i}`); + return route.matcher(url, options, request); + }); + + if (route) { + return route; + } +}; + +FetchMock$1.getNativeFetch = function () { + const func = this.realFetch || (this.isSandbox && this.config.fetch); + if (!func) { + throw new Error( + 'fetch-mock: Falling back to network only available on global fetch-mock, or by setting config.fetch on sandboxed fetch-mock' + ); + } + return patchNativeFetchForSafari(func); +}; + +FetchMock$1.recordCall = function (obj) { + debug$2('Recording fetch call', obj); + if (obj) { + this._calls.push(obj); + } +}; + +var fetchHandler = FetchMock$1; + +var globToRegexp = function (glob, opts) { + if (typeof glob !== 'string') { + throw new TypeError('Expected a string'); + } + + var str = String(glob); + + // The regexp we are building, as a string. + var reStr = ""; + + // Whether we are matching so called "extended" globs (like bash) and should + // support single character matching, matching ranges of characters, group + // matching, etc. + var extended = opts ? !!opts.extended : false; + + // When globstar is _false_ (default), '/foo/*' is translated a regexp like + // '^\/foo\/.*$' which will match any string beginning with '/foo/' + // When globstar is _true_, '/foo/*' is translated to regexp like + // '^\/foo\/[^/]*$' which will match any string beginning with '/foo/' BUT + // which does not have a '/' to the right of it. + // E.g. with '/foo/*' these will match: '/foo/bar', '/foo/bar.txt' but + // these will not '/foo/bar/baz', '/foo/bar/baz.txt' + // Lastely, when globstar is _true_, '/foo/**' is equivelant to '/foo/*' when + // globstar is _false_ + var globstar = opts ? !!opts.globstar : false; + + // If we are doing extended matching, this boolean is true when we are inside + // a group (eg {*.html,*.js}), and false otherwise. + var inGroup = false; + + // RegExp flags (eg "i" ) to pass in to RegExp constructor. + var flags = opts && typeof( opts.flags ) === "string" ? opts.flags : ""; + + var c; + for (var i = 0, len = str.length; i < len; i++) { + c = str[i]; + + switch (c) { + case "/": + case "$": + case "^": + case "+": + case ".": + case "(": + case ")": + case "=": + case "!": + case "|": + reStr += "\\" + c; + break; + + case "?": + if (extended) { + reStr += "."; + break; + } + + case "[": + case "]": + if (extended) { + reStr += c; + break; + } + + case "{": + if (extended) { + inGroup = true; + reStr += "("; + break; + } + + case "}": + if (extended) { + inGroup = false; + reStr += ")"; + break; + } + + case ",": + if (inGroup) { + reStr += "|"; + break; + } + reStr += "\\" + c; + break; + + case "*": + // Move over all consecutive "*"'s. + // Also store the previous and next characters + var prevChar = str[i - 1]; + var starCount = 1; + while(str[i + 1] === "*") { + starCount++; + i++; + } + var nextChar = str[i + 1]; + + if (!globstar) { + // globstar is disabled, so treat any number of "*" as one + reStr += ".*"; + } else { + // globstar is enabled, so determine if this is a globstar segment + var isGlobstar = starCount > 1 // multiple "*"'s + && (prevChar === "/" || prevChar === undefined) // from the start of the segment + && (nextChar === "/" || nextChar === undefined); // to the end of the segment + + if (isGlobstar) { + // it's a globstar, so match zero or more path segments + reStr += "((?:[^/]*(?:\/|$))*)"; + i++; // move over the "/" + } else { + // it's not a globstar, so only match one path segment + reStr += "([^/]*)"; + } + } + break; + + default: + reStr += c; + } + } + + // When regexp 'g' flag is specified don't + // constrain the regular expression with ^ & $ + if (!flags || !~flags.indexOf('g')) { + reStr = "^" + reStr + "$"; + } + + return new RegExp(reStr, flags); +}; + +/** + * Expose `pathToRegexp`. + */ +var pathToRegexp_1 = pathToRegexp; +var parse_1 = parse$3; +var compile_1 = compile; +var tokensToFunction_1 = tokensToFunction; +var tokensToRegExp_1 = tokensToRegExp; + +/** + * Default configs. + */ +var DEFAULT_DELIMITER = '/'; +var DEFAULT_DELIMITERS = './'; + +/** + * The main path matching regexp utility. + * + * @type {RegExp} + */ +var PATH_REGEXP = new RegExp([ + // Match escaped characters that would otherwise appear in future matches. + // This allows the user to escape special characters that won't transform. + '(\\\\.)', + // Match Express-style parameters and un-named parameters with a prefix + // and optional suffixes. Matches appear as: + // + // ":test(\\d+)?" => ["test", "\d+", undefined, "?"] + // "(\\d+)" => [undefined, undefined, "\d+", undefined] + '(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?' +].join('|'), 'g'); + +/** + * Parse a string for the raw tokens. + * + * @param {string} str + * @param {Object=} options + * @return {!Array} + */ +function parse$3 (str, options) { + var tokens = []; + var key = 0; + var index = 0; + var path = ''; + var defaultDelimiter = (options && options.delimiter) || DEFAULT_DELIMITER; + var delimiters = (options && options.delimiters) || DEFAULT_DELIMITERS; + var pathEscaped = false; + var res; + + while ((res = PATH_REGEXP.exec(str)) !== null) { + var m = res[0]; + var escaped = res[1]; + var offset = res.index; + path += str.slice(index, offset); + index = offset + m.length; + + // Ignore already escaped sequences. + if (escaped) { + path += escaped[1]; + pathEscaped = true; + continue + } + + var prev = ''; + var next = str[index]; + var name = res[2]; + var capture = res[3]; + var group = res[4]; + var modifier = res[5]; + + if (!pathEscaped && path.length) { + var k = path.length - 1; + + if (delimiters.indexOf(path[k]) > -1) { + prev = path[k]; + path = path.slice(0, k); + } + } + + // Push the current path onto the tokens. + if (path) { + tokens.push(path); + path = ''; + pathEscaped = false; + } + + var partial = prev !== '' && next !== undefined && next !== prev; + var repeat = modifier === '+' || modifier === '*'; + var optional = modifier === '?' || modifier === '*'; + var delimiter = prev || defaultDelimiter; + var pattern = capture || group; + + tokens.push({ + name: name || key++, + prefix: prev, + delimiter: delimiter, + optional: optional, + repeat: repeat, + partial: partial, + pattern: pattern ? escapeGroup(pattern) : '[^' + escapeString(delimiter) + ']+?' + }); + } + + // Push any remaining characters. + if (path || index < str.length) { + tokens.push(path + str.substr(index)); + } + + return tokens +} + +/** + * Compile a string to a template function for the path. + * + * @param {string} str + * @param {Object=} options + * @return {!function(Object=, Object=)} + */ +function compile (str, options) { + return tokensToFunction(parse$3(str, options)) +} + +/** + * Expose a method for transforming tokens into the path function. + */ +function tokensToFunction (tokens) { + // Compile all the tokens into regexps. + var matches = new Array(tokens.length); + + // Compile all the patterns before compilation. + for (var i = 0; i < tokens.length; i++) { + if (typeof tokens[i] === 'object') { + matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$'); + } + } + + return function (data, options) { + var path = ''; + var encode = (options && options.encode) || encodeURIComponent; + + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + + if (typeof token === 'string') { + path += token; + continue + } + + var value = data ? data[token.name] : undefined; + var segment; + + if (Array.isArray(value)) { + if (!token.repeat) { + throw new TypeError('Expected "' + token.name + '" to not repeat, but got array') + } + + if (value.length === 0) { + if (token.optional) continue + + throw new TypeError('Expected "' + token.name + '" to not be empty') + } + + for (var j = 0; j < value.length; j++) { + segment = encode(value[j], token); + + if (!matches[i].test(segment)) { + throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '"') + } + + path += (j === 0 ? token.prefix : token.delimiter) + segment; + } + + continue + } + + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + segment = encode(String(value), token); + + if (!matches[i].test(segment)) { + throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but got "' + segment + '"') + } + + path += token.prefix + segment; + continue + } + + if (token.optional) { + // Prepend partial segment prefixes. + if (token.partial) path += token.prefix; + + continue + } + + throw new TypeError('Expected "' + token.name + '" to be ' + (token.repeat ? 'an array' : 'a string')) + } + + return path + } +} + +/** + * Escape a regular expression string. + * + * @param {string} str + * @return {string} + */ +function escapeString (str) { + return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1') +} + +/** + * Escape the capturing group by escaping special characters and meaning. + * + * @param {string} group + * @return {string} + */ +function escapeGroup (group) { + return group.replace(/([=!:$/()])/g, '\\$1') +} + +/** + * Get the flags for a regexp from the options. + * + * @param {Object} options + * @return {string} + */ +function flags (options) { + return options && options.sensitive ? '' : 'i' +} + +/** + * Pull out keys from a regexp. + * + * @param {!RegExp} path + * @param {Array=} keys + * @return {!RegExp} + */ +function regexpToRegexp (path, keys) { + if (!keys) return path + + // Use a negative lookahead to match only capturing groups. + var groups = path.source.match(/\((?!\?)/g); + + if (groups) { + for (var i = 0; i < groups.length; i++) { + keys.push({ + name: i, + prefix: null, + delimiter: null, + optional: false, + repeat: false, + partial: false, + pattern: null + }); + } + } + + return path +} + +/** + * Transform an array into a regexp. + * + * @param {!Array} path + * @param {Array=} keys + * @param {Object=} options + * @return {!RegExp} + */ +function arrayToRegexp (path, keys, options) { + var parts = []; + + for (var i = 0; i < path.length; i++) { + parts.push(pathToRegexp(path[i], keys, options).source); + } + + return new RegExp('(?:' + parts.join('|') + ')', flags(options)) +} + +/** + * Create a path regexp from string input. + * + * @param {string} path + * @param {Array=} keys + * @param {Object=} options + * @return {!RegExp} + */ +function stringToRegexp (path, keys, options) { + return tokensToRegExp(parse$3(path, options), keys, options) +} + +/** + * Expose a function for taking tokens and returning a RegExp. + * + * @param {!Array} tokens + * @param {Array=} keys + * @param {Object=} options + * @return {!RegExp} + */ +function tokensToRegExp (tokens, keys, options) { + options = options || {}; + + var strict = options.strict; + var start = options.start !== false; + var end = options.end !== false; + var delimiter = escapeString(options.delimiter || DEFAULT_DELIMITER); + var delimiters = options.delimiters || DEFAULT_DELIMITERS; + var endsWith = [].concat(options.endsWith || []).map(escapeString).concat('$').join('|'); + var route = start ? '^' : ''; + var isEndDelimited = tokens.length === 0; + + // Iterate over the tokens and create our regexp string. + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + + if (typeof token === 'string') { + route += escapeString(token); + isEndDelimited = i === tokens.length - 1 && delimiters.indexOf(token[token.length - 1]) > -1; + } else { + var capture = token.repeat + ? '(?:' + token.pattern + ')(?:' + escapeString(token.delimiter) + '(?:' + token.pattern + '))*' + : token.pattern; + + if (keys) keys.push(token); + + if (token.optional) { + if (token.partial) { + route += escapeString(token.prefix) + '(' + capture + ')?'; + } else { + route += '(?:' + escapeString(token.prefix) + '(' + capture + '))?'; + } + } else { + route += escapeString(token.prefix) + '(' + capture + ')'; + } + } + } + + if (end) { + if (!strict) route += '(?:' + delimiter + ')?'; + + route += endsWith === '$' ? '$' : '(?=' + endsWith + ')'; + } else { + if (!strict) route += '(?:' + delimiter + '(?=' + endsWith + '))?'; + if (!isEndDelimited) route += '(?=' + delimiter + '|' + endsWith + ')'; + } + + return new RegExp(route, flags(options)) +} + +/** + * Normalize the given path string, returning a regular expression. + * + * An empty array can be passed in for the keys, which will hold the + * placeholder key descriptions. For example, using `/user/:id`, `keys` will + * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`. + * + * @param {(string|RegExp|Array)} path + * @param {Array=} keys + * @param {Object=} options + * @return {!RegExp} + */ +function pathToRegexp (path, keys, options) { + if (path instanceof RegExp) { + return regexpToRegexp(path, keys) + } + + if (Array.isArray(path)) { + return arrayToRegexp(/** @type {!Array} */ (path), keys, options) + } + + return stringToRegexp(/** @type {string} */ (path), keys, options) +} +pathToRegexp_1.parse = parse_1; +pathToRegexp_1.compile = compile_1; +pathToRegexp_1.tokensToFunction = tokensToFunction_1; +pathToRegexp_1.tokensToRegExp = tokensToRegExp_1; + +var isSubset_1 = createCommonjsModule(function (module, exports) { + +Object.defineProperty(exports, '__esModule', { + value: true +}); +/** + * Check if an object is contained within another object. + * + * Returns `true` if: + * - all enumerable keys of *subset* are also enumerable in *superset*, and + * - every value assigned to an enumerable key of *subset* strictly equals + * the value assigned to the same key of *superset* – or is a subset of it. + * + * @param {Object} superset + * @param {Object} subset + * + * @returns {Boolean} + * + * @module is-subset + * @function default + * @alias isSubset + */ +var isSubset = (function (_isSubset) { + function isSubset(_x, _x2) { + return _isSubset.apply(this, arguments); + } + + isSubset.toString = function () { + return _isSubset.toString(); + }; + + return isSubset; +})(function (superset, subset) { + if (typeof superset !== 'object' || superset === null || (typeof subset !== 'object' || subset === null)) return false; + + return Object.keys(subset).every(function (key) { + if (!superset.propertyIsEnumerable(key)) return false; + + var subsetItem = subset[key]; + var supersetItem = superset[key]; + if (typeof subsetItem === 'object' && subsetItem !== null ? !isSubset(supersetItem, subsetItem) : supersetItem !== subsetItem) return false; + + return true; + }); +}); + +exports['default'] = isSubset; +module.exports = exports['default']; +}); + +unwrapExports(isSubset_1); + +var lodash_isequal = createCommonjsModule(function (module, exports) { +/** + * Lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright JS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + nullTag = '[object Null]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + undefinedTag = '[object Undefined]', + weakMapTag = '[object WeakMap]'; + +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** Used to identify `toStringTag` values of typed arrays. */ +var typedArrayTags = {}; +typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = +typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = +typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = +typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = +typedArrayTags[uint32Tag] = true; +typedArrayTags[argsTag] = typedArrayTags[arrayTag] = +typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = +typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = +typedArrayTags[errorTag] = typedArrayTags[funcTag] = +typedArrayTags[mapTag] = typedArrayTags[numberTag] = +typedArrayTags[objectTag] = typedArrayTags[regexpTag] = +typedArrayTags[setTag] = typedArrayTags[stringTag] = +typedArrayTags[weakMapTag] = false; + +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); + +/** Detect free variable `exports`. */ +var freeExports = exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; + +/** Detect free variable `process` from Node.js. */ +var freeProcess = moduleExports && freeGlobal.process; + +/** Used to access faster Node.js helpers. */ +var nodeUtil = (function() { + try { + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} +}()); + +/* Node.js helper references. */ +var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + +/** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ +function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; +} + +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; +} + +/** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ +function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; +} + +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +/** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ +function baseUnary(func) { + return function(value) { + return func(value); + }; +} + +/** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function cacheHas(cache, key) { + return cache.has(key); +} + +/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function getValue(object, key) { + return object == null ? undefined : object[key]; +} + +/** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ +function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; +} + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +/** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ +function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; +} + +/** Used for built-in method references. */ +var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + +/** Used to detect overreaching core-js shims. */ +var coreJsData = root['__core-js_shared__']; + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** Used to detect methods masquerading as native. */ +var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; +}()); + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; + +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); + +/** Built-in value references. */ +var Buffer = moduleExports ? root.Buffer : undefined, + Symbol = root.Symbol, + Uint8Array = root.Uint8Array, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + symToStringTag = Symbol ? Symbol.toStringTag : undefined; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeKeys = overArg(Object.keys, Object); + +/* Built-in method references that are verified to be native. */ +var DataView = getNative(root, 'DataView'), + Map = getNative(root, 'Map'), + Promise = getNative(root, 'Promise'), + Set = getNative(root, 'Set'), + WeakMap = getNative(root, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); + +/** Used to detect maps, sets, and weakmaps. */ +var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; + +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ +function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; +} + +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; +} + +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; +} + +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); +} + +/** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ +function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; +} + +// Add methods to `Hash`. +Hash.prototype.clear = hashClear; +Hash.prototype['delete'] = hashDelete; +Hash.prototype.get = hashGet; +Hash.prototype.has = hashHas; +Hash.prototype.set = hashSet; + +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; + this.size = 0; +} + +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; +} + +/** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; +} + +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; +} + +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ +function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; +} + +// Add methods to `ListCache`. +ListCache.prototype.clear = listCacheClear; +ListCache.prototype['delete'] = listCacheDelete; +ListCache.prototype.get = listCacheGet; +ListCache.prototype.has = listCacheHas; +ListCache.prototype.set = listCacheSet; + +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ +function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; +} + +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; +} + +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function mapCacheGet(key) { + return getMapData(this, key).get(key); +} + +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function mapCacheHas(key) { + return getMapData(this, key).has(key); +} + +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ +function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; +} + +// Add methods to `MapCache`. +MapCache.prototype.clear = mapCacheClear; +MapCache.prototype['delete'] = mapCacheDelete; +MapCache.prototype.get = mapCacheGet; +MapCache.prototype.has = mapCacheHas; +MapCache.prototype.set = mapCacheSet; + +/** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ +function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } +} + +/** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ +function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; +} + +/** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ +function setCacheHas(value) { + return this.__data__.has(value); +} + +// Add methods to `SetCache`. +SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; +SetCache.prototype.has = setCacheHas; + +/** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; +} + +/** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ +function stackClear() { + this.__data__ = new ListCache; + this.size = 0; +} + +/** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; +} + +/** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function stackGet(key) { + return this.__data__.get(key); +} + +/** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function stackHas(key) { + return this.__data__.has(key); +} + +/** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ +function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; +} + +// Add methods to `Stack`. +Stack.prototype.clear = stackClear; +Stack.prototype['delete'] = stackDelete; +Stack.prototype.get = stackGet; +Stack.prototype.has = stackHas; +Stack.prototype.set = stackSet; + +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; +} + +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; +} + +/** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ +function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); +} + +/** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); +} + +/** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ +function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; +} + +/** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ +function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); +} + +/** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other); + + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); +} + +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ +function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); +} + +/** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ +function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; +} + +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; +} + +/** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ +function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; +} + +/** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; +} + +/** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; +} + +/** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ +function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); +} + +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ +function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; +} + +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; +} + +/** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ +function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; +} + +/** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ +var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); +}; + +/** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +var getTag = baseGetTag; + +// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. +if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; +} + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); +} + +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); +} + +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); +} + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; +} + +/** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ +function objectToString(value) { + return nativeObjectToString.call(value); +} + +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; +} + +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); +}; + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +/** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ +var isBuffer = nativeIsBuffer || stubFalse; + +/** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ +function isEqual(value, other) { + return baseIsEqual(value, other); +} + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; +} + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return value != null && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ +var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} + +/** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ +function stubArray() { + return []; +} + +/** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ +function stubFalse() { + return false; +} + +module.exports = isEqual; +}); + +const { debug: debug$3 } = debug_1; + + + + +const { + headers: headerUtils, + getPath, + getQuery, + normalizeUrl: normalizeUrl$1, +} = requestUtils; + + +const debuggableUrlFunc = (func) => (url) => { + debug$3('Actual url:', url); + return func(url); +}; + +const stringMatchers = { + begin: (targetString) => + debuggableUrlFunc((url) => url.indexOf(targetString) === 0), + end: (targetString) => + debuggableUrlFunc( + (url) => url.substr(-targetString.length) === targetString + ), + glob: (targetString) => { + const urlRX = globToRegexp(targetString); + return debuggableUrlFunc((url) => urlRX.test(url)); + }, + express: (targetString) => { + const urlRX = pathToRegexp_1(targetString); + return debuggableUrlFunc((url) => urlRX.test(getPath(url))); + }, + path: (targetString) => + debuggableUrlFunc((url) => getPath(url) === targetString), +}; + +const getHeaderMatcher = ({ headers: expectedHeaders }) => { + debug$3('Generating header matcher'); + if (!expectedHeaders) { + debug$3(' No header expectations defined - skipping'); + return; + } + const expectation = headerUtils.toLowerCase(expectedHeaders); + debug$3(' Expected headers:', expectation); + return (url, { headers = {} }) => { + debug$3('Attempting to match headers'); + const lowerCaseHeaders = headerUtils.toLowerCase( + headerUtils.normalize(headers) + ); + debug$3(' Expected headers:', expectation); + debug$3(' Actual headers:', lowerCaseHeaders); + return Object.keys(expectation).every((headerName) => + headerUtils.equal(lowerCaseHeaders[headerName], expectation[headerName]) + ); + }; +}; + +const getMethodMatcher = ({ method: expectedMethod }) => { + debug$3('Generating method matcher'); + if (!expectedMethod) { + debug$3(' No method expectations defined - skipping'); + return; + } + debug$3(' Expected method:', expectedMethod); + return (url, { method }) => { + debug$3('Attempting to match method'); + const actualMethod = method ? method.toLowerCase() : 'get'; + debug$3(' Expected method:', expectedMethod); + debug$3(' Actual method:', actualMethod); + return expectedMethod === actualMethod; + }; +}; + +const getQueryStringMatcher = ({ query: passedQuery }) => { + debug$3('Generating query parameters matcher'); + if (!passedQuery) { + debug$3(' No query parameters expectations defined - skipping'); + return; + } + const expectedQuery = querystring.parse(querystring.stringify(passedQuery)); + debug$3(' Expected query parameters:', passedQuery); + const keys = Object.keys(expectedQuery); + return (url) => { + debug$3('Attempting to match query parameters'); + const query = querystring.parse(getQuery(url)); + debug$3(' Expected query parameters:', expectedQuery); + debug$3(' Actual query parameters:', query); + return keys.every((key) => { + if (Array.isArray(query[key])) { + if (!Array.isArray(expectedQuery[key])) { + return false; + } else { + return lodash_isequal(query[key].sort(), expectedQuery[key].sort()); + } + } + return query[key] === expectedQuery[key]; + }); + }; +}; + +const getParamsMatcher = ({ params: expectedParams, url: matcherUrl }) => { + debug$3('Generating path parameters matcher'); + if (!expectedParams) { + debug$3(' No path parameters expectations defined - skipping'); + return; + } + if (!/express:/.test(matcherUrl)) { + throw new Error( + 'fetch-mock: matching on params is only possible when using an express: matcher' + ); + } + debug$3(' Expected path parameters:', expectedParams); + const expectedKeys = Object.keys(expectedParams); + const keys = []; + const re = pathToRegexp_1(matcherUrl.replace(/^express:/, ''), keys); + return (url) => { + debug$3('Attempting to match path parameters'); + const vals = re.exec(getPath(url)) || []; + vals.shift(); + const params = keys.reduce( + (map, { name }, i) => + vals[i] ? Object.assign(map, { [name]: vals[i] }) : map, + {} + ); + debug$3(' Expected path parameters:', expectedParams); + debug$3(' Actual path parameters:', params); + return expectedKeys.every((key) => params[key] === expectedParams[key]); + }; +}; + +const getBodyMatcher = (route, fetchMock) => { + const matchPartialBody = fetchMock.getOption('matchPartialBody', route); + const { body: expectedBody } = route; + + debug$3('Generating body matcher'); + return (url, { body, method = 'get' }) => { + debug$3('Attempting to match body'); + if (method.toLowerCase() === 'get') { + debug$3(' GET request - skip matching body'); + // GET requests don’t send a body so the body matcher should be ignored for them + return true; + } + + let sentBody = body; + + try { + debug$3(' Parsing request body as JSON'); + sentBody = JSON.parse(body); + } catch (err) { + debug$3(' Failed to parse request body as JSON', err); + } + debug$3('Expected body:', expectedBody); + debug$3('Actual body:', sentBody); + if (matchPartialBody) { + debug$3('matchPartialBody is true - checking for partial match only'); + } + + return ( + sentBody && + (matchPartialBody + ? isSubset_1(sentBody, expectedBody) + : lodash_isequal(sentBody, expectedBody)) + ); + }; +}; + +const getFullUrlMatcher = (route, matcherUrl, query) => { + // if none of the special syntaxes apply, it's just a simple string match + // but we have to be careful to normalize the url we check and the name + // of the route to allow for e.g. http://it.at.there being indistinguishable + // from http://it.at.there/ once we start generating Request/Url objects + debug$3(' Matching using full url', matcherUrl); + const expectedUrl = normalizeUrl$1(matcherUrl); + debug$3(' Normalised url to:', matcherUrl); + if (route.identifier === matcherUrl) { + debug$3(' Updating route identifier to match normalized url:', matcherUrl); + route.identifier = expectedUrl; + } + + return (matcherUrl) => { + debug$3('Expected url:', expectedUrl); + debug$3('Actual url:', matcherUrl); + if (query && expectedUrl.indexOf('?')) { + debug$3('Ignoring query string when matching url'); + return matcherUrl.indexOf(expectedUrl) === 0; + } + return normalizeUrl$1(matcherUrl) === expectedUrl; + }; +}; + +const getFunctionMatcher = ({ functionMatcher }) => { + debug$3('Detected user defined function matcher', functionMatcher); + return (...args) => { + debug$3('Calling function matcher with arguments', args); + return functionMatcher(...args); + }; +}; + +const getUrlMatcher = (route) => { + debug$3('Generating url matcher'); + const { url: matcherUrl, query } = route; + + if (matcherUrl === '*') { + debug$3(' Using universal * rule to match any url'); + return () => true; + } + + if (matcherUrl instanceof RegExp) { + debug$3(' Using regular expression to match url:', matcherUrl); + return (url) => matcherUrl.test(url); + } + + if (matcherUrl.href) { + debug$3(` Using URL object to match url`, matcherUrl); + return getFullUrlMatcher(route, matcherUrl.href, query); + } + + for (const shorthand in stringMatchers) { + if (matcherUrl.indexOf(shorthand + ':') === 0) { + debug$3(` Using ${shorthand}: pattern to match url`, matcherUrl); + const urlFragment = matcherUrl.replace(new RegExp(`^${shorthand}:`), ''); + return stringMatchers[shorthand](urlFragment); + } + } + + return getFullUrlMatcher(route, matcherUrl, query); +}; + +var matchers = [ + { name: 'query', matcher: getQueryStringMatcher }, + { name: 'method', matcher: getMethodMatcher }, + { name: 'headers', matcher: getHeaderMatcher }, + { name: 'params', matcher: getParamsMatcher }, + { name: 'body', matcher: getBodyMatcher, usesBody: true }, + { name: 'functionMatcher', matcher: getFunctionMatcher }, + { name: 'url', matcher: getUrlMatcher }, +]; + +const { debug: debug$4, setDebugNamespace, getDebug: getDebug$2 } = debug_1; + +const isUrlMatcher = (matcher) => + matcher instanceof RegExp || + typeof matcher === 'string' || + (typeof matcher === 'object' && 'href' in matcher); + +const isFunctionMatcher = (matcher) => typeof matcher === 'function'; + +class Route { + constructor(args, fetchMock) { + this.fetchMock = fetchMock; + const debug = getDebug$2('compileRoute()'); + debug('Compiling route'); + this.init(args); + this.sanitize(); + this.validate(); + this.generateMatcher(); + this.limit(); + this.delayResponse(); + } + + validate() { + if (!('response' in this)) { + throw new Error('fetch-mock: Each route must define a response'); + } + + if (!Route.registeredMatchers.some(({ name }) => name in this)) { + throw new Error( + "fetch-mock: Each route must specify some criteria for matching calls to fetch. To match all calls use '*'" + ); + } + } + + init(args) { + const [matcher, response, options = {}] = args; + + const routeConfig = {}; + + if (isUrlMatcher(matcher) || isFunctionMatcher(matcher)) { + routeConfig.matcher = matcher; + } else { + Object.assign(routeConfig, matcher); + } + + if (typeof response !== 'undefined') { + routeConfig.response = response; + } + + Object.assign(routeConfig, options); + Object.assign(this, routeConfig); + } + + sanitize() { + const debug = getDebug$2('sanitize()'); + debug('Sanitizing route properties'); + + if (this.method) { + debug(`Converting method ${this.method} to lower case`); + this.method = this.method.toLowerCase(); + } + if (isUrlMatcher(this.matcher)) { + debug('Mock uses a url matcher', this.matcher); + this.url = this.matcher; + delete this.matcher; + } + + this.functionMatcher = this.matcher || this.functionMatcher; + + debug('Setting route.identifier...'); + debug(` route.name is ${this.name}`); + debug(` route.url is ${this.url}`); + debug(` route.functionMatcher is ${this.functionMatcher}`); + this.identifier = this.name || this.url || this.functionMatcher; + debug(` -> route.identifier set to ${this.identifier}`); + } + + generateMatcher() { + setDebugNamespace('generateMatcher()'); + debug$4('Compiling matcher for route'); + + const activeMatchers = Route.registeredMatchers + .map( + ({ name, matcher, usesBody }) => + this[name] && { matcher: matcher(this, this.fetchMock), usesBody } + ) + .filter((matcher) => Boolean(matcher)); + + this.usesBody = activeMatchers.some(({ usesBody }) => usesBody); + + debug$4('Compiled matcher for route'); + setDebugNamespace(); + this.matcher = (url, options = {}, request) => + activeMatchers.every(({ matcher }) => matcher(url, options, request)); + } + + limit() { + const debug = getDebug$2('limit()'); + debug('Limiting number of requests to handle by route'); + if (!this.repeat) { + debug( + ' No `repeat` value set on route. Will match any number of requests' + ); + return; + } + + debug(` Route set to repeat ${this.repeat} times`); + const matcher = this.matcher; + let timesLeft = this.repeat; + this.matcher = (url, options) => { + const match = timesLeft && matcher(url, options); + if (match) { + timesLeft--; + return true; + } + }; + this.reset = () => (timesLeft = this.repeat); + } + + delayResponse() { + const debug = getDebug$2('delayResponse()'); + debug(`Applying response delay settings`); + if (this.delay) { + debug(` Wrapping response in delay of ${this.delay} miliseconds`); + const response = this.response; + this.response = () => { + debug(`Delaying response by ${this.delay} miliseconds`); + return new Promise((res) => + setTimeout(() => res(response), this.delay) + ); + }; + } else { + debug( + ` No delay set on route. Will respond 'immediately' (but asynchronously)` + ); + } + } + + static addMatcher(matcher) { + Route.registeredMatchers.push(matcher); + } +} + +Route.registeredMatchers = []; + +matchers.forEach(Route.addMatcher); + +var Route_1 = Route; + +const { setDebugPhase: setDebugPhase$2, setDebugNamespace: setDebugNamespace$1, debug: debug$5 } = debug_1; +const { normalizeUrl: normalizeUrl$2 } = requestUtils; + +const FetchMock$2 = {}; +const isName = (nameOrMatcher) => + typeof nameOrMatcher === 'string' && /^[\da-zA-Z\-]+$/.test(nameOrMatcher); + +const filterCallsWithMatcher = function (matcher, options = {}, calls) { + ({ matcher } = new Route_1( + [Object.assign({ matcher, response: 'ok' }, options)], + this + )); + return calls.filter(({ url, options }) => + matcher(normalizeUrl$2(url), options) + ); +}; + +const formatDebug = (func) => { + return function (...args) { + setDebugPhase$2('inspect'); + const result = func.call(this, ...args); + setDebugPhase$2(); + return result; + }; +}; + +const callObjToArray = (obj) => { + if (!obj) { + return undefined; + } + const { url, options, request, identifier, isUnmatched, response } = obj; + const arr = [url, options]; + arr.request = request; + arr.identifier = identifier; + arr.isUnmatched = isUnmatched; + arr.response = response; + return arr; +}; + +FetchMock$2.filterCalls = function (nameOrMatcher, options) { + debug$5('Filtering fetch calls'); + let calls = this._calls; + let matcher = '*'; + + if ([true, 'matched'].includes(nameOrMatcher)) { + debug$5(`Filter provided is ${nameOrMatcher}. Returning matched calls only`); + calls = calls.filter(({ isUnmatched }) => !isUnmatched); + } else if ([false, 'unmatched'].includes(nameOrMatcher)) { + debug$5( + `Filter provided is ${nameOrMatcher}. Returning unmatched calls only` + ); + calls = calls.filter(({ isUnmatched }) => isUnmatched); + } else if (typeof nameOrMatcher === 'undefined') { + debug$5(`Filter provided is undefined. Returning all calls`); + calls = calls; + } else if (isName(nameOrMatcher)) { + debug$5( + `Filter provided, looks like the name of a named route. Returning only calls handled by that route` + ); + calls = calls.filter(({ identifier }) => identifier === nameOrMatcher); + } else { + matcher = nameOrMatcher === '*' ? '*' : normalizeUrl$2(nameOrMatcher); + if (this.routes.some(({ identifier }) => identifier === matcher)) { + debug$5( + `Filter provided, ${nameOrMatcher}, identifies a route. Returning only calls handled by that route` + ); + calls = calls.filter((call) => call.identifier === matcher); + } + } + + if ((options || matcher !== '*') && calls.length) { + if (typeof options === 'string') { + options = { method: options }; + } + debug$5( + 'Compiling filter and options to route in order to filter all calls', + nameOrMatcher + ); + calls = filterCallsWithMatcher.call(this, matcher, options, calls); + } + debug$5(`Retrieved ${calls.length} calls`); + return calls.map(callObjToArray); +}; + +FetchMock$2.calls = formatDebug(function (nameOrMatcher, options) { + debug$5('retrieving matching calls'); + return this.filterCalls(nameOrMatcher, options); +}); + +FetchMock$2.lastCall = formatDebug(function (nameOrMatcher, options) { + debug$5('retrieving last matching call'); + return [...this.filterCalls(nameOrMatcher, options)].pop(); +}); + +FetchMock$2.lastUrl = formatDebug(function (nameOrMatcher, options) { + debug$5('retrieving url of last matching call'); + return (this.lastCall(nameOrMatcher, options) || [])[0]; +}); + +FetchMock$2.lastOptions = formatDebug(function (nameOrMatcher, options) { + debug$5('retrieving options of last matching call'); + return (this.lastCall(nameOrMatcher, options) || [])[1]; +}); + +FetchMock$2.lastResponse = formatDebug(function (nameOrMatcher, options) { + debug$5('retrieving respose of last matching call'); + console.warn(`When doing all the following: +- using node-fetch +- responding with a real network response (using spy() or fallbackToNetwork) +- using \`fetchMock.LastResponse()\` +- awaiting the body content +... the response will hang unless your source code also awaits the response body. +This is an unavoidable consequence of the nodejs implementation of streams. +`); + const response = (this.lastCall(nameOrMatcher, options) || []).response; + try { + const clonedResponse = response.clone(); + return clonedResponse; + } catch (err) { + Object.entries(response._fmResults).forEach(([name, result]) => { + response[name] = () => result; + }); + return response; + } +}); + +FetchMock$2.called = formatDebug(function (nameOrMatcher, options) { + debug$5('checking if matching call was made'); + return Boolean(this.filterCalls(nameOrMatcher, options).length); +}); + +FetchMock$2.flush = formatDebug(async function (waitForResponseMethods) { + setDebugNamespace$1('flush'); + debug$5( + `flushing all fetch calls. ${ + waitForResponseMethods ? '' : 'Not ' + }waiting for response bodies to complete download` + ); + + const queuedPromises = this._holdingPromises; + this._holdingPromises = []; + debug$5(`${queuedPromises.length} fetch calls to be awaited`); + + await Promise.all(queuedPromises); + debug$5(`All fetch calls have completed`); + if (waitForResponseMethods && this._holdingPromises.length) { + debug$5(`Awaiting all fetch bodies to download`); + await this.flush(waitForResponseMethods); + debug$5(`All fetch bodies have completed downloading`); + } + setDebugNamespace$1(); +}); + +FetchMock$2.done = formatDebug(function (nameOrMatcher) { + setDebugPhase$2('inspect'); + setDebugNamespace$1('done'); + debug$5('Checking to see if expected calls have been made'); + let routesToCheck; + + if (nameOrMatcher && typeof nameOrMatcher !== 'boolean') { + debug$5( + 'Checking to see if expected calls have been made for single route:', + nameOrMatcher + ); + routesToCheck = [{ identifier: nameOrMatcher }]; + } else { + debug$5('Checking to see if expected calls have been made for all routes'); + routesToCheck = this.routes; + } + + // Can't use array.every because would exit after first failure, which would + // break the logging + const result = routesToCheck + .map(({ identifier }) => { + if (!this.called(identifier)) { + debug$5('No calls made for route:', identifier); + console.warn(`Warning: ${identifier} not called`); // eslint-disable-line + return false; + } + + const expectedTimes = ( + this.routes.find((r) => r.identifier === identifier) || {} + ).repeat; + + if (!expectedTimes) { + debug$5( + 'Route has been called at least once, and no expectation of more set:', + identifier + ); + return true; + } + const actualTimes = this.filterCalls(identifier).length; + + debug$5(`Route called ${actualTimes} times:`, identifier); + if (expectedTimes > actualTimes) { + debug$5( + `Route called ${actualTimes} times, but expected ${expectedTimes}:`, + identifier + ); + console.warn( + `Warning: ${identifier} only called ${actualTimes} times, but ${expectedTimes} expected` + ); // eslint-disable-line + return false; + } else { + return true; + } + }) + .every((isDone) => isDone); + + setDebugNamespace$1(); + setDebugPhase$2(); + return result; +}); + +var inspecting = FetchMock$2; + +const { debug: debug$6 } = debug_1; + + + + + +const FetchMock$3 = Object.assign({}, fetchHandler, setUpAndTearDown, inspecting); + +FetchMock$3.addMatcher = function (matcher) { + Route_1.addMatcher(matcher); +}; + +FetchMock$3.config = { + fallbackToNetwork: false, + includeContentLength: true, + sendAsJson: true, + warnOnFallback: true, + overwriteRoutes: undefined, +}; + +FetchMock$3.createInstance = function () { + debug$6('Creating fetch-mock instance'); + const instance = Object.create(FetchMock$3); + instance._uncompiledRoutes = (this._uncompiledRoutes || []).slice(); + instance.routes = instance._uncompiledRoutes.map((config) => + this.compileRoute(config) + ); + instance.fallbackResponse = this.fallbackResponse || undefined; + instance.config = Object.assign({}, this.config || FetchMock$3.config); + instance._calls = []; + instance._holdingPromises = []; + instance.bindMethods(); + return instance; +}; + +FetchMock$3.compileRoute = function (config) { + return new Route_1(config, this); +}; + +FetchMock$3.bindMethods = function () { + this.fetchHandler = FetchMock$3.fetchHandler.bind(this); + this.reset = this.restore = FetchMock$3.reset.bind(this); + this.resetHistory = FetchMock$3.resetHistory.bind(this); + this.resetBehavior = FetchMock$3.resetBehavior.bind(this); +}; + +FetchMock$3.sandbox = function () { + debug$6('Creating sandboxed fetch-mock instance'); + // this construct allows us to create a fetch-mock instance which is also + // a callable function, while circumventing circularity when defining the + // object that this function should be bound to + const fetchMockProxy = (url, options) => sandbox.fetchHandler(url, options); + + const sandbox = Object.assign( + fetchMockProxy, // Ensures that the entire returned object is a callable function + FetchMock$3, // prototype methods + this.createInstance(), // instance data + { + Headers: this.config.Headers, + Request: this.config.Request, + Response: this.config.Response, + } + ); + + sandbox.bindMethods(); + sandbox.isSandbox = true; + sandbox.default = sandbox; + return sandbox; +}; + +FetchMock$3.getOption = function (name, route = {}) { + return name in route ? route[name] : this.config[name]; +}; + +var lib$1 = FetchMock$3; + +var lib$2 = createCommonjsModule(function (module, exports) { + +function _(message, opts) { + return `${opts && opts.context ? opts.context : "Value"} ${message}.`; +} + +function type(V) { + if (V === null) { + return "Null"; + } + switch (typeof V) { + case "undefined": + return "Undefined"; + case "boolean": + return "Boolean"; + case "number": + return "Number"; + case "string": + return "String"; + case "symbol": + return "Symbol"; + case "object": + // Falls through + case "function": + // Falls through + default: + // Per ES spec, typeof returns an implemention-defined value that is not any of the existing ones for + // uncallable non-standard exotic objects. Yet Type() which the Web IDL spec depends on returns Object for + // such cases. So treat the default case as an object. + return "Object"; + } +} + +// Round x to the nearest integer, choosing the even integer if it lies halfway between two. +function evenRound(x) { + // There are four cases for numbers with fractional part being .5: + // + // case | x | floor(x) | round(x) | expected | x <> 0 | x % 1 | x & 1 | example + // 1 | 2n + 0.5 | 2n | 2n + 1 | 2n | > | 0.5 | 0 | 0.5 -> 0 + // 2 | 2n + 1.5 | 2n + 1 | 2n + 2 | 2n + 2 | > | 0.5 | 1 | 1.5 -> 2 + // 3 | -2n - 0.5 | -2n - 1 | -2n | -2n | < | -0.5 | 0 | -0.5 -> 0 + // 4 | -2n - 1.5 | -2n - 2 | -2n - 1 | -2n - 2 | < | -0.5 | 1 | -1.5 -> -2 + // (where n is a non-negative integer) + // + // Branch here for cases 1 and 4 + if ((x > 0 && (x % 1) === +0.5 && (x & 1) === 0) || + (x < 0 && (x % 1) === -0.5 && (x & 1) === 1)) { + return censorNegativeZero(Math.floor(x)); + } + + return censorNegativeZero(Math.round(x)); +} + +function integerPart(n) { + return censorNegativeZero(Math.trunc(n)); +} + +function sign(x) { + return x < 0 ? -1 : 1; +} + +function modulo(x, y) { + // https://tc39.github.io/ecma262/#eqn-modulo + // Note that http://stackoverflow.com/a/4467559/3191 does NOT work for large modulos + const signMightNotMatch = x % y; + if (sign(y) !== sign(signMightNotMatch)) { + return signMightNotMatch + y; + } + return signMightNotMatch; +} + +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} + +function createIntegerConversion(bitLength, typeOpts) { + const isSigned = !typeOpts.unsigned; + + let lowerBound; + let upperBound; + if (bitLength === 64) { + upperBound = Math.pow(2, 53) - 1; + lowerBound = !isSigned ? 0 : -Math.pow(2, 53) + 1; + } else if (!isSigned) { + lowerBound = 0; + upperBound = Math.pow(2, bitLength) - 1; + } else { + lowerBound = -Math.pow(2, bitLength - 1); + upperBound = Math.pow(2, bitLength - 1) - 1; + } + + const twoToTheBitLength = Math.pow(2, bitLength); + const twoToOneLessThanTheBitLength = Math.pow(2, bitLength - 1); + + return (V, opts) => { + if (opts === undefined) { + opts = {}; + } + + let x = +V; + x = censorNegativeZero(x); // Spec discussion ongoing: https://github.com/heycam/webidl/issues/306 + + if (opts.enforceRange) { + if (!Number.isFinite(x)) { + throw new TypeError(_("is not a finite number", opts)); + } + + x = integerPart(x); + + if (x < lowerBound || x > upperBound) { + throw new TypeError(_( + `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`, opts)); + } + + return x; + } + + if (!Number.isNaN(x) && opts.clamp) { + x = Math.min(Math.max(x, lowerBound), upperBound); + x = evenRound(x); + return x; + } + + if (!Number.isFinite(x) || x === 0) { + return 0; + } + x = integerPart(x); + + // Math.pow(2, 64) is not accurately representable in JavaScript, so try to avoid these per-spec operations if + // possible. Hopefully it's an optimization for the non-64-bitLength cases too. + if (x >= lowerBound && x <= upperBound) { + return x; + } + + // These will not work great for bitLength of 64, but oh well. See the README for more details. + x = modulo(x, twoToTheBitLength); + if (isSigned && x >= twoToOneLessThanTheBitLength) { + return x - twoToTheBitLength; + } + return x; + }; +} + +exports.any = V => { + return V; +}; + +exports.void = function () { + return undefined; +}; + +exports.boolean = function (val) { + return !!val; +}; + +exports.byte = createIntegerConversion(8, { unsigned: false }); +exports.octet = createIntegerConversion(8, { unsigned: true }); + +exports.short = createIntegerConversion(16, { unsigned: false }); +exports["unsigned short"] = createIntegerConversion(16, { unsigned: true }); + +exports.long = createIntegerConversion(32, { unsigned: false }); +exports["unsigned long"] = createIntegerConversion(32, { unsigned: true }); + +exports["long long"] = createIntegerConversion(64, { unsigned: false }); +exports["unsigned long long"] = createIntegerConversion(64, { unsigned: true }); + +exports.double = (V, opts) => { + const x = +V; + + if (!Number.isFinite(x)) { + throw new TypeError(_("is not a finite floating-point value", opts)); + } + + return x; +}; + +exports["unrestricted double"] = V => { + const x = +V; + + return x; +}; + +exports.float = (V, opts) => { + const x = +V; + + if (!Number.isFinite(x)) { + throw new TypeError(_("is not a finite floating-point value", opts)); + } + + if (Object.is(x, -0)) { + return x; + } + + const y = Math.fround(x); + + if (!Number.isFinite(y)) { + throw new TypeError(_("is outside the range of a single-precision floating-point value", opts)); + } + + return y; +}; + +exports["unrestricted float"] = V => { + const x = +V; + + if (isNaN(x)) { + return x; + } + + if (Object.is(x, -0)) { + return x; + } + + return Math.fround(x); +}; + +exports.DOMString = function (V, opts) { + if (opts === undefined) { + opts = {}; + } + + if (opts.treatNullAsEmptyString && V === null) { + return ""; + } + + if (typeof V === "symbol") { + throw new TypeError(_("is a symbol, which cannot be converted to a string", opts)); + } + + return String(V); +}; + +exports.ByteString = (V, opts) => { + const x = exports.DOMString(V, opts); + let c; + for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { + if (c > 255) { + throw new TypeError(_("is not a valid ByteString", opts)); + } + } + + return x; +}; + +exports.USVString = (V, opts) => { + const S = exports.DOMString(V, opts); + const n = S.length; + const U = []; + for (let i = 0; i < n; ++i) { + const c = S.charCodeAt(i); + if (c < 0xD800 || c > 0xDFFF) { + U.push(String.fromCodePoint(c)); + } else if (0xDC00 <= c && c <= 0xDFFF) { + U.push(String.fromCodePoint(0xFFFD)); + } else if (i === n - 1) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + const d = S.charCodeAt(i + 1); + if (0xDC00 <= d && d <= 0xDFFF) { + const a = c & 0x3FF; + const b = d & 0x3FF; + U.push(String.fromCodePoint((2 << 15) + ((2 << 9) * a) + b)); + ++i; + } else { + U.push(String.fromCodePoint(0xFFFD)); + } + } + } + + return U.join(""); +}; + +exports.object = (V, opts) => { + if (type(V) !== "Object") { + throw new TypeError(_("is not an object", opts)); + } + + return V; +}; + +// Not exported, but used in Function and VoidFunction. + +// Neither Function nor VoidFunction is defined with [TreatNonObjectAsNull], so +// handling for that is omitted. +function convertCallbackFunction(V, opts) { + if (typeof V !== "function") { + throw new TypeError(_("is not a function", opts)); + } + return V; +} + +[ + Error, + ArrayBuffer, // The IsDetachedBuffer abstract operation is not exposed in JS + DataView, Int8Array, Int16Array, Int32Array, Uint8Array, + Uint16Array, Uint32Array, Uint8ClampedArray, Float32Array, Float64Array +].forEach(func => { + const name = func.name; + const article = /^[AEIOU]/.test(name) ? "an" : "a"; + exports[name] = (V, opts) => { + if (!(V instanceof func)) { + throw new TypeError(_(`is not ${article} ${name} object`, opts)); + } + + return V; + }; +}); + +// Common definitions + +exports.ArrayBufferView = (V, opts) => { + if (!ArrayBuffer.isView(V)) { + throw new TypeError(_("is not a view on an ArrayBuffer object", opts)); + } + + return V; +}; + +exports.BufferSource = (V, opts) => { + if (!(ArrayBuffer.isView(V) || V instanceof ArrayBuffer)) { + throw new TypeError(_("is not an ArrayBuffer object or a view on one", opts)); + } + + return V; +}; + +exports.DOMTimeStamp = exports["unsigned long long"]; + +exports.Function = convertCallbackFunction; + +exports.VoidFunction = convertCallbackFunction; +}); +var lib_1 = lib$2.any; +var lib_2 = lib$2.octet; +var lib_3 = lib$2.DOMString; +var lib_4 = lib$2.ByteString; +var lib_5 = lib$2.USVString; +var lib_6 = lib$2.object; +var lib_7 = lib$2.ArrayBufferView; +var lib_8 = lib$2.BufferSource; +var lib_9 = lib$2.DOMTimeStamp; +var lib_10 = lib$2.Function; +var lib_11 = lib$2.VoidFunction; + +var utils = createCommonjsModule(function (module, exports) { + +// Returns "Type(value) is Object" in ES terminology. +function isObject(value) { + return typeof value === "object" && value !== null || typeof value === "function"; +} + +function getReferenceToBytes(bufferSource) { + // Node.js' Buffer does not allow subclassing for now, so we can get away with a prototype object check for perf. + if (Object.getPrototypeOf(bufferSource) === Buffer$1.prototype) { + return bufferSource; + } + if (bufferSource instanceof ArrayBuffer) { + return Buffer$1.from(bufferSource); + } + return Buffer$1.from(bufferSource.buffer, bufferSource.byteOffset, bufferSource.byteLength); +} + +function getCopyToBytes(bufferSource) { + return Buffer$1.from(getReferenceToBytes(bufferSource)); +} + +function mixin(target, source) { + const keys = Object.getOwnPropertyNames(source); + for (let i = 0; i < keys.length; ++i) { + if (keys[i] in target) { + continue; + } + + Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i])); + } +} + +const wrapperSymbol = Symbol("wrapper"); +const implSymbol = Symbol("impl"); +const sameObjectCaches = Symbol("SameObject caches"); + +function getSameObject(wrapper, prop, creator) { + if (!wrapper[sameObjectCaches]) { + wrapper[sameObjectCaches] = Object.create(null); + } + + if (prop in wrapper[sameObjectCaches]) { + return wrapper[sameObjectCaches][prop]; + } + + wrapper[sameObjectCaches][prop] = creator(); + return wrapper[sameObjectCaches][prop]; +} + +function wrapperForImpl(impl) { + return impl ? impl[wrapperSymbol] : null; +} + +function implForWrapper(wrapper) { + return wrapper ? wrapper[implSymbol] : null; +} + +function tryWrapperForImpl(impl) { + const wrapper = wrapperForImpl(impl); + return wrapper ? wrapper : impl; +} + +function tryImplForWrapper(wrapper) { + const impl = implForWrapper(wrapper); + return impl ? impl : wrapper; +} + +const iterInternalSymbol = Symbol("internal"); +const IteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())); + +function isArrayIndexPropName(P) { + if (typeof P !== "string") { + return false; + } + const i = P >>> 0; + if (i === Math.pow(2, 32) - 1) { + return false; + } + const s = `${i}`; + if (P !== s) { + return false; + } + return true; +} + +const supportsPropertyIndex = Symbol("supports property index"); +const supportedPropertyIndices = Symbol("supported property indices"); +const supportsPropertyName = Symbol("supports property name"); +const supportedPropertyNames = Symbol("supported property names"); +const indexedGet = Symbol("indexed property get"); +const indexedSetNew = Symbol("indexed property set new"); +const indexedSetExisting = Symbol("indexed property set existing"); +const namedGet = Symbol("named property get"); +const namedSetNew = Symbol("named property set new"); +const namedSetExisting = Symbol("named property set existing"); +const namedDelete = Symbol("named property delete"); + +module.exports = exports = { + isObject, + getReferenceToBytes, + getCopyToBytes, + mixin, + wrapperSymbol, + implSymbol, + getSameObject, + wrapperForImpl, + implForWrapper, + tryWrapperForImpl, + tryImplForWrapper, + iterInternalSymbol, + IteratorPrototype, + isArrayIndexPropName, + supportsPropertyIndex, + supportedPropertyIndices, + supportsPropertyName, + supportedPropertyNames, + indexedGet, + indexedSetNew, + indexedSetExisting, + namedGet, + namedSetNew, + namedSetExisting, + namedDelete +}; +}); + +const combiningMarks = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{11000}-\u{11002}\u{11038}-\u{11046}\u{1107F}-\u{11082}\u{110B0}-\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{11134}\u{11173}\u{11180}-\u{11182}\u{111B3}-\u{111C0}\u{111CA}-\u{111CC}\u{1122C}-\u{11237}\u{1123E}\u{112DF}-\u{112EA}\u{11300}-\u{11303}\u{1133C}\u{1133E}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11357}\u{11362}\u{11363}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11435}-\u{11446}\u{114B0}-\u{114C3}\u{115AF}-\u{115B5}\u{115B8}-\u{115C0}\u{115DC}\u{115DD}\u{11630}-\u{11640}\u{116AB}-\u{116B7}\u{1171D}-\u{1172B}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A39}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A5B}\u{11A8A}-\u{11A99}\u{11C2F}-\u{11C36}\u{11C38}-\u{11C3F}\u{11C92}-\u{11CA7}\u{11CA9}-\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F51}-\u{16F7E}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1D165}-\u{1D169}\u{1D16D}-\u{1D172}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]/u; +const combiningClassVirama = /[\u094D\u09CD\u0A4D\u0ACD\u0B4D\u0BCD\u0C4D\u0CCD\u0D3B\u0D3C\u0D4D\u0DCA\u0E3A\u0F84\u1039\u103A\u1714\u1734\u17D2\u1A60\u1B44\u1BAA\u1BAB\u1BF2\u1BF3\u2D7F\uA806\uA8C4\uA953\uA9C0\uAAF6\uABED\u{10A3F}\u{11046}\u{1107F}\u{110B9}\u{11133}\u{11134}\u{111C0}\u{11235}\u{112EA}\u{1134D}\u{11442}\u{114C2}\u{115BF}\u{1163F}\u{116B6}\u{1172B}\u{11A34}\u{11A47}\u{11A99}\u{11C3F}\u{11D44}\u{11D45}]/u; +const validZWNJ = /[\u0620\u0626\u0628\u062A-\u062E\u0633-\u063F\u0641-\u0647\u0649\u064A\u066E\u066F\u0678-\u0687\u069A-\u06BF\u06C1\u06C2\u06CC\u06CE\u06D0\u06D1\u06FA-\u06FC\u06FF\u0712-\u0714\u071A-\u071D\u071F-\u0727\u0729\u072B\u072D\u072E\u074E-\u0758\u075C-\u076A\u076D-\u0770\u0772\u0775-\u0777\u077A-\u077F\u07CA-\u07EA\u0841-\u0845\u0848\u084A-\u0853\u0855\u0860\u0862-\u0865\u0868\u08A0-\u08A9\u08AF\u08B0\u08B3\u08B4\u08B6-\u08B8\u08BA-\u08BD\u1807\u1820-\u1877\u1887-\u18A8\u18AA\uA840-\uA872\u{10AC0}-\u{10AC4}\u{10ACD}\u{10AD3}-\u{10ADC}\u{10ADE}-\u{10AE0}\u{10AEB}-\u{10AEE}\u{10B80}\u{10B82}\u{10B86}-\u{10B88}\u{10B8A}\u{10B8B}\u{10B8D}\u{10B90}\u{10BAD}\u{10BAE}\u{1E900}-\u{1E943}][\xAD\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u061C\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CBF\u0CC6\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFEFF\uFFF9-\uFFFB\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110BD}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111CA}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C3F}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*\u200C[\xAD\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u061C\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CBF\u0CC6\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFEFF\uFFF9-\uFFFB\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110BD}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111CA}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C3F}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*[\u0620\u0622-\u063F\u0641-\u064A\u066E\u066F\u0671-\u0673\u0675-\u06D3\u06D5\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u077F\u07CA-\u07EA\u0840-\u0855\u0860\u0862-\u0865\u0867-\u086A\u08A0-\u08AC\u08AE-\u08B4\u08B6-\u08BD\u1807\u1820-\u1877\u1887-\u18A8\u18AA\uA840-\uA871\u{10AC0}-\u{10AC5}\u{10AC7}\u{10AC9}\u{10ACA}\u{10ACE}-\u{10AD6}\u{10AD8}-\u{10AE1}\u{10AE4}\u{10AEB}-\u{10AEF}\u{10B80}-\u{10B91}\u{10BA9}-\u{10BAE}\u{1E900}-\u{1E943}]/u; +const bidiDomain = /[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05F0-\u05F4\u0600-\u0605\u0608\u060B\u060D\u061B\u061C\u061E-\u064A\u0660-\u0669\u066B-\u066F\u0671-\u06D5\u06DD\u06E5\u06E6\u06EE\u06EF\u06FA-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08E2\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A33}\u{10A40}-\u{10A47}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10CFF}\u{10E60}-\u{10E7E}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}]/u; +const bidiS1LTR = /[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02BB-\u02C1\u02D0\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0482\u048A-\u052F\u0531-\u0556\u0559-\u055F\u0561-\u0587\u0589\u0903-\u0939\u093B\u093D-\u0940\u0949-\u094C\u094E-\u0950\u0958-\u0961\u0964-\u0980\u0982\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD-\u09C0\u09C7\u09C8\u09CB\u09CC\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09FA\u09FC\u09FD\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD-\u0AC0\u0AC9\u0ACB\u0ACC\u0AD0\u0AE0\u0AE1\u0AE6-\u0AF0\u0AF9\u0B02\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40\u0B47\u0B48\u0B4B\u0B4C\u0B57\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE\u0BBF\u0BC1\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD0\u0BD7\u0BE6-\u0BF2\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C41-\u0C44\u0C58-\u0C5A\u0C60\u0C61\u0C66-\u0C6F\u0C7F\u0C80\u0C82\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD-\u0CC4\u0CC6-\u0CC8\u0CCA\u0CCB\u0CD5\u0CD6\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D4E\u0D4F\u0D54-\u0D61\u0D66-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCF-\u0DD1\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E4F-\u0E5B\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F17\u0F1A-\u0F34\u0F36\u0F38\u0F3E-\u0F47\u0F49-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FDA\u1000-\u102C\u1031\u1038\u103B\u103C\u103F-\u1057\u105A-\u105D\u1061-\u1070\u1075-\u1081\u1083\u1084\u1087-\u108C\u108E-\u109C\u109E-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u167F\u1681-\u169A\u16A0-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1735\u1736\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5\u17C7\u17C8\u17D4-\u17DA\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930\u1931\u1933-\u1938\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A19\u1A1A\u1A1E-\u1A55\u1A57\u1A61\u1A63\u1A64\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1B04-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B4B\u1B50-\u1B6A\u1B74-\u1B7C\u1B82-\u1BA1\u1BA6\u1BA7\u1BAA\u1BAE-\u1BE5\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2\u1BF3\u1BFC-\u1C2B\u1C34\u1C35\u1C3B-\u1C49\u1C4D-\u1C88\u1CC0-\u1CC7\u1CD3\u1CE1\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5-\u1CF7\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2188\u2336-\u237A\u2395\u249C-\u24E9\u26AC\u2800-\u28FF\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u302E\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u3190-\u31BA\u31F0-\u321C\u3220-\u324F\u3260-\u327B\u327F-\u32B0\u32C0-\u32CB\u32D0-\u32FE\u3300-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA60C\uA610-\uA62B\uA640-\uA66E\uA680-\uA69D\uA6A0-\uA6EF\uA6F2-\uA6F7\uA722-\uA787\uA789-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA824\uA827\uA830-\uA837\uA840-\uA873\uA880-\uA8C3\uA8CE-\uA8D9\uA8F2-\uA8FD\uA900-\uA925\uA92E-\uA946\uA952\uA953\uA95F-\uA97C\uA983-\uA9B2\uA9B4\uA9B5\uA9BA\uA9BB\uA9BD-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA2F\uAA30\uAA33\uAA34\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA7B\uAA7D-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAAEB\uAAEE-\uAAF5\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB65\uAB70-\uABE4\uABE6\uABE7\uABE9-\uABEC\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1013F}\u{1018D}\u{1018E}\u{101D0}-\u{101FC}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{11000}\u{11002}-\u{11037}\u{11047}-\u{1104D}\u{11066}-\u{1106F}\u{11082}-\u{110B2}\u{110B7}\u{110B8}\u{110BB}-\u{110C1}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11103}-\u{11126}\u{1112C}\u{11136}-\u{11143}\u{11150}-\u{11172}\u{11174}-\u{11176}\u{11182}-\u{111B5}\u{111BF}-\u{111C9}\u{111CD}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1122E}\u{11232}\u{11233}\u{11235}\u{11238}-\u{1123D}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112DE}\u{112E0}-\u{112E2}\u{112F0}-\u{112F9}\u{11302}\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}-\u{1133F}\u{11341}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11400}-\u{11437}\u{11440}\u{11441}\u{11445}\u{11447}-\u{11459}\u{1145B}\u{1145D}\u{11480}-\u{114B2}\u{114B9}\u{114BB}-\u{114BE}\u{114C1}\u{114C4}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B1}\u{115B8}-\u{115BB}\u{115BE}\u{115C1}-\u{115DB}\u{11600}-\u{11632}\u{1163B}\u{1163C}\u{1163E}\u{11641}-\u{11644}\u{11650}-\u{11659}\u{11680}-\u{116AA}\u{116AC}\u{116AE}\u{116AF}\u{116B6}\u{116C0}-\u{116C9}\u{11700}-\u{11719}\u{11720}\u{11721}\u{11726}\u{11730}-\u{1173F}\u{118A0}-\u{118F2}\u{118FF}\u{11A00}\u{11A07}\u{11A08}\u{11A0B}-\u{11A32}\u{11A39}\u{11A3A}\u{11A3F}-\u{11A46}\u{11A50}\u{11A57}\u{11A58}\u{11A5C}-\u{11A83}\u{11A86}-\u{11A89}\u{11A97}\u{11A9A}-\u{11A9C}\u{11A9E}-\u{11AA2}\u{11AC0}-\u{11AF8}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2F}\u{11C3E}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11CA9}\u{11CB1}\u{11CB4}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D50}-\u{11D59}\u{12000}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{13000}-\u{1342E}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}\u{16A6F}\u{16AD0}-\u{16AED}\u{16AF5}\u{16B00}-\u{16B2F}\u{16B37}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16F00}-\u{16F44}\u{16F50}-\u{16F7E}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{17000}-\u{187EC}\u{18800}-\u{18AF2}\u{1B000}-\u{1B11E}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}\u{1BC9F}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D166}\u{1D16A}-\u{1D172}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D360}-\u{1D371}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6DA}\u{1D6DC}-\u{1D714}\u{1D716}-\u{1D74E}\u{1D750}-\u{1D788}\u{1D78A}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1D800}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}-\u{1DA8B}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F169}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{20000}-\u{2A6D6}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/u; +const bidiS1RTL = /[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05F0-\u05F4\u0608\u060B\u060D\u061B\u061C\u061E-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A33}\u{10A40}-\u{10A47}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10CFF}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}]/u; +const bidiS2 = /^[\0-\x08\x0E-\x1B!-@\[-`\{-\x84\x86-\xA9\xAB-\xB4\xB6-\xB9\xBB-\xBF\xD7\xF7\u02B9\u02BA\u02C2-\u02CF\u02D2-\u02DF\u02E5-\u02ED\u02EF-\u036F\u0374\u0375\u037E\u0384\u0385\u0387\u03F6\u0483-\u0489\u058A\u058D-\u058F\u0591-\u05C7\u05D0-\u05EA\u05F0-\u05F4\u0600-\u061C\u061E-\u070D\u070F-\u074A\u074D-\u07B1\u07C0-\u07FA\u0800-\u082D\u0830-\u083E\u0840-\u085B\u085E\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09F2\u09F3\u09FB\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AF1\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0BF3-\u0BFA\u0C00\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C78-\u0C7E\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E3F\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39-\u0F3D\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1390-\u1399\u1400\u169B\u169C\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DB\u17DD\u17F0-\u17F9\u1800-\u180E\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1940\u1944\u1945\u19DE-\u19FF\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u200B-\u200D\u200F-\u2027\u202F-\u205E\u2060-\u2064\u206A-\u2070\u2074-\u207E\u2080-\u208E\u20A0-\u20BF\u20D0-\u20F0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u2150-\u215F\u2189-\u218B\u2190-\u2335\u237B-\u2394\u2396-\u2426\u2440-\u244A\u2460-\u249B\u24EA-\u26AB\u26AD-\u27FF\u2900-\u2B73\u2B76-\u2B95\u2B98-\u2BB9\u2BBD-\u2BC8\u2BCA-\u2BD2\u2BEC-\u2BEF\u2CE5-\u2CEA\u2CEF-\u2CF1\u2CF9-\u2CFF\u2D7F\u2DE0-\u2E49\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3001-\u3004\u3008-\u3020\u302A-\u302D\u3030\u3036\u3037\u303D-\u303F\u3099-\u309C\u30A0\u30FB\u31C0-\u31E3\u321D\u321E\u3250-\u325F\u327C-\u327E\u32B1-\u32BF\u32CC-\u32CF\u3377-\u337A\u33DE\u33DF\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA60D-\uA60F\uA66F-\uA67F\uA69E\uA69F\uA6F0\uA6F1\uA700-\uA721\uA788\uA802\uA806\uA80B\uA825\uA826\uA828-\uA82B\uA838\uA839\uA874-\uA877\uA8C4\uA8C5\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1D-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC1\uFBD3-\uFD3F\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFD\uFE00-\uFE19\uFE20-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFE70-\uFE74\uFE76-\uFEFC\uFEFF\uFF01-\uFF20\uFF3B-\uFF40\uFF5B-\uFF65\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFF9-\uFFFD\u{10101}\u{10140}-\u{1018C}\u{10190}-\u{1019B}\u{101A0}\u{101FD}\u{102E0}-\u{102FB}\u{10376}-\u{1037A}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{1091F}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A33}\u{10A38}-\u{10A3A}\u{10A3F}-\u{10A47}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE6}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B39}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10CFF}\u{10E60}-\u{10E7E}\u{11001}\u{11038}-\u{11046}\u{11052}-\u{11065}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111CA}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{11660}-\u{1166C}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D200}-\u{1D245}\u{1D300}-\u{1D356}\u{1D6DB}\u{1D715}\u{1D74F}\u{1D789}\u{1D7C3}\u{1D7CE}-\u{1D7FF}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8D6}\u{1E900}-\u{1E94A}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}\u{1EEF0}\u{1EEF1}\u{1F000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F100}-\u{1F10C}\u{1F16A}\u{1F16B}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D4}\u{1F6E0}-\u{1F6EC}\u{1F6F0}-\u{1F6F8}\u{1F700}-\u{1F773}\u{1F780}-\u{1F7D4}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F900}-\u{1F90B}\u{1F910}-\u{1F93E}\u{1F940}-\u{1F94C}\u{1F950}-\u{1F96B}\u{1F980}-\u{1F997}\u{1F9C0}\u{1F9D0}-\u{1F9E6}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*$/u; +const bidiS3 = /[0-9\xB2\xB3\xB9\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05F0-\u05F4\u0600-\u0605\u0608\u060B\u060D\u061B\u061C\u061E-\u064A\u0660-\u0669\u066B-\u066F\u0671-\u06D5\u06DD\u06E5\u06E6\u06EE-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08E2\u200F\u2070\u2074-\u2079\u2080-\u2089\u2488-\u249B\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\u{102E1}-\u{102FB}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A33}\u{10A40}-\u{10A47}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10CFF}\u{10E60}-\u{10E7E}\u{1D7CE}-\u{1D7FF}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}\u{1F100}-\u{1F10A}][\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111CA}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]*$/u; +const bidiS4EN = /[0-9\xB2\xB3\xB9\u06F0-\u06F9\u2070\u2074-\u2079\u2080-\u2089\u2488-\u249B\uFF10-\uFF19\u{102E1}-\u{102FB}\u{1D7CE}-\u{1D7FF}\u{1F100}-\u{1F10A}]/u; +const bidiS4AN = /[\u0600-\u0605\u0660-\u0669\u066B\u066C\u06DD\u08E2\u{10E60}-\u{10E7E}]/u; +const bidiS5 = /^[\0-\x08\x0E-\x1B!-\x84\x86-\u0377\u037A-\u037F\u0384-\u038A\u038C\u038E-\u03A1\u03A3-\u052F\u0531-\u0556\u0559-\u055F\u0561-\u0587\u0589\u058A\u058D-\u058F\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0606\u0607\u0609\u060A\u060C\u060E-\u061A\u064B-\u065F\u066A\u0670\u06D6-\u06DC\u06DE-\u06E4\u06E7-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07F6-\u07F9\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09FD\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AF1\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B77\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BFA\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C78-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4F\u0D54-\u0D63\u0D66-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E3A\u0E3F-\u0E5B\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F47\u0F49-\u0F6C\u0F71-\u0F97\u0F99-\u0FBC\u0FBE-\u0FCC\u0FCE-\u0FDA\u1000-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u137C\u1380-\u1399\u13A0-\u13F5\u13F8-\u13FD\u1400-\u167F\u1681-\u169C\u16A0-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1736\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17DD\u17E0-\u17E9\u17F0-\u17F9\u1800-\u180E\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1940\u1944-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u19DE-\u1A1B\u1A1E-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1AB0-\u1ABE\u1B00-\u1B4B\u1B50-\u1B7C\u1B80-\u1BF3\u1BFC-\u1C37\u1C3B-\u1C49\u1C4D-\u1C88\u1CC0-\u1CC7\u1CD0-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FC4\u1FC6-\u1FD3\u1FD6-\u1FDB\u1FDD-\u1FEF\u1FF2-\u1FF4\u1FF6-\u1FFE\u200B-\u200E\u2010-\u2027\u202F-\u205E\u2060-\u2064\u206A-\u2071\u2074-\u208E\u2090-\u209C\u20A0-\u20BF\u20D0-\u20F0\u2100-\u218B\u2190-\u2426\u2440-\u244A\u2460-\u2B73\u2B76-\u2B95\u2B98-\u2BB9\u2BBD-\u2BC8\u2BCA-\u2BD2\u2BEC-\u2BEF\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CF3\u2CF9-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2E49\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3001-\u303F\u3041-\u3096\u3099-\u30FF\u3105-\u312E\u3131-\u318E\u3190-\u31BA\u31C0-\u31E3\u31F0-\u321E\u3220-\u32FE\u3300-\u4DB5\u4DC0-\u9FEA\uA000-\uA48C\uA490-\uA4C6\uA4D0-\uA62B\uA640-\uA6F7\uA700-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA82B\uA830-\uA839\uA840-\uA877\uA880-\uA8C5\uA8CE-\uA8D9\uA8E0-\uA8FD\uA900-\uA953\uA95F-\uA97C\uA980-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA5C-\uAAC2\uAADB-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB65\uAB70-\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1E\uFB29\uFD3E\uFD3F\uFDFD\uFE00-\uFE19\uFE20-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFEFF\uFF01-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFF9-\uFFFD\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}-\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1018E}\u{10190}-\u{1019B}\u{101A0}\u{101D0}-\u{101FD}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{102E0}-\u{102FB}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{1037A}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{1091F}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10B39}-\u{10B3F}\u{11000}-\u{1104D}\u{11052}-\u{1106F}\u{1107F}-\u{110C1}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11100}-\u{11134}\u{11136}-\u{11143}\u{11150}-\u{11176}\u{11180}-\u{111CD}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1123E}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112EA}\u{112F0}-\u{112F9}\u{11300}-\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133C}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11400}-\u{11459}\u{1145B}\u{1145D}\u{11480}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B5}\u{115B8}-\u{115DD}\u{11600}-\u{11644}\u{11650}-\u{11659}\u{11660}-\u{1166C}\u{11680}-\u{116B7}\u{116C0}-\u{116C9}\u{11700}-\u{11719}\u{1171D}-\u{1172B}\u{11730}-\u{1173F}\u{118A0}-\u{118F2}\u{118FF}\u{11A00}-\u{11A47}\u{11A50}-\u{11A83}\u{11A86}-\u{11A9C}\u{11A9E}-\u{11AA2}\u{11AC0}-\u{11AF8}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C36}\u{11C38}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11C92}-\u{11CA7}\u{11CA9}-\u{11CB6}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D47}\u{11D50}-\u{11D59}\u{12000}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{13000}-\u{1342E}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}\u{16A6F}\u{16AD0}-\u{16AED}\u{16AF0}-\u{16AF5}\u{16B00}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16F00}-\u{16F44}\u{16F50}-\u{16F7E}\u{16F8F}-\u{16F9F}\u{16FE0}\u{16FE1}\u{17000}-\u{187EC}\u{18800}-\u{18AF2}\u{1B000}-\u{1B11E}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}-\u{1BCA3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D1E8}\u{1D200}-\u{1D245}\u{1D300}-\u{1D356}\u{1D360}-\u{1D371}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D7CB}\u{1D7CE}-\u{1DA8B}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{1EEF0}\u{1EEF1}\u{1F000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F100}-\u{1F10C}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F16B}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D4}\u{1F6E0}-\u{1F6EC}\u{1F6F0}-\u{1F6F8}\u{1F700}-\u{1F773}\u{1F780}-\u{1F7D4}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F900}-\u{1F90B}\u{1F910}-\u{1F93E}\u{1F940}-\u{1F94C}\u{1F950}-\u{1F96B}\u{1F980}-\u{1F997}\u{1F9C0}\u{1F9D0}-\u{1F9E6}\u{20000}-\u{2A6D6}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]*$/u; +const bidiS6 = /[0-9A-Za-z\xAA\xB2\xB3\xB5\xB9\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02BB-\u02C1\u02D0\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0482\u048A-\u052F\u0531-\u0556\u0559-\u055F\u0561-\u0587\u0589\u06F0-\u06F9\u0903-\u0939\u093B\u093D-\u0940\u0949-\u094C\u094E-\u0950\u0958-\u0961\u0964-\u0980\u0982\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD-\u09C0\u09C7\u09C8\u09CB\u09CC\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09FA\u09FC\u09FD\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD-\u0AC0\u0AC9\u0ACB\u0ACC\u0AD0\u0AE0\u0AE1\u0AE6-\u0AF0\u0AF9\u0B02\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40\u0B47\u0B48\u0B4B\u0B4C\u0B57\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE\u0BBF\u0BC1\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD0\u0BD7\u0BE6-\u0BF2\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C41-\u0C44\u0C58-\u0C5A\u0C60\u0C61\u0C66-\u0C6F\u0C7F\u0C80\u0C82\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD-\u0CC4\u0CC6-\u0CC8\u0CCA\u0CCB\u0CD5\u0CD6\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D4E\u0D4F\u0D54-\u0D61\u0D66-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCF-\u0DD1\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E4F-\u0E5B\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F17\u0F1A-\u0F34\u0F36\u0F38\u0F3E-\u0F47\u0F49-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FDA\u1000-\u102C\u1031\u1038\u103B\u103C\u103F-\u1057\u105A-\u105D\u1061-\u1070\u1075-\u1081\u1083\u1084\u1087-\u108C\u108E-\u109C\u109E-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u167F\u1681-\u169A\u16A0-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1735\u1736\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5\u17C7\u17C8\u17D4-\u17DA\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930\u1931\u1933-\u1938\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A19\u1A1A\u1A1E-\u1A55\u1A57\u1A61\u1A63\u1A64\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1B04-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B4B\u1B50-\u1B6A\u1B74-\u1B7C\u1B82-\u1BA1\u1BA6\u1BA7\u1BAA\u1BAE-\u1BE5\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2\u1BF3\u1BFC-\u1C2B\u1C34\u1C35\u1C3B-\u1C49\u1C4D-\u1C88\u1CC0-\u1CC7\u1CD3\u1CE1\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5-\u1CF7\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E\u2070\u2071\u2074-\u2079\u207F-\u2089\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2188\u2336-\u237A\u2395\u2488-\u24E9\u26AC\u2800-\u28FF\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u302E\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u3190-\u31BA\u31F0-\u321C\u3220-\u324F\u3260-\u327B\u327F-\u32B0\u32C0-\u32CB\u32D0-\u32FE\u3300-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA60C\uA610-\uA62B\uA640-\uA66E\uA680-\uA69D\uA6A0-\uA6EF\uA6F2-\uA6F7\uA722-\uA787\uA789-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA824\uA827\uA830-\uA837\uA840-\uA873\uA880-\uA8C3\uA8CE-\uA8D9\uA8F2-\uA8FD\uA900-\uA925\uA92E-\uA946\uA952\uA953\uA95F-\uA97C\uA983-\uA9B2\uA9B4\uA9B5\uA9BA\uA9BB\uA9BD-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA2F\uAA30\uAA33\uAA34\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA7B\uAA7D-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAAEB\uAAEE-\uAAF5\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB65\uAB70-\uABE4\uABE6\uABE7\uABE9-\uABEC\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1013F}\u{1018D}\u{1018E}\u{101D0}-\u{101FC}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{102E1}-\u{102FB}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{11000}\u{11002}-\u{11037}\u{11047}-\u{1104D}\u{11066}-\u{1106F}\u{11082}-\u{110B2}\u{110B7}\u{110B8}\u{110BB}-\u{110C1}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11103}-\u{11126}\u{1112C}\u{11136}-\u{11143}\u{11150}-\u{11172}\u{11174}-\u{11176}\u{11182}-\u{111B5}\u{111BF}-\u{111C9}\u{111CD}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1122E}\u{11232}\u{11233}\u{11235}\u{11238}-\u{1123D}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112DE}\u{112E0}-\u{112E2}\u{112F0}-\u{112F9}\u{11302}\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}-\u{1133F}\u{11341}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11400}-\u{11437}\u{11440}\u{11441}\u{11445}\u{11447}-\u{11459}\u{1145B}\u{1145D}\u{11480}-\u{114B2}\u{114B9}\u{114BB}-\u{114BE}\u{114C1}\u{114C4}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B1}\u{115B8}-\u{115BB}\u{115BE}\u{115C1}-\u{115DB}\u{11600}-\u{11632}\u{1163B}\u{1163C}\u{1163E}\u{11641}-\u{11644}\u{11650}-\u{11659}\u{11680}-\u{116AA}\u{116AC}\u{116AE}\u{116AF}\u{116B6}\u{116C0}-\u{116C9}\u{11700}-\u{11719}\u{11720}\u{11721}\u{11726}\u{11730}-\u{1173F}\u{118A0}-\u{118F2}\u{118FF}\u{11A00}\u{11A07}\u{11A08}\u{11A0B}-\u{11A32}\u{11A39}\u{11A3A}\u{11A3F}-\u{11A46}\u{11A50}\u{11A57}\u{11A58}\u{11A5C}-\u{11A83}\u{11A86}-\u{11A89}\u{11A97}\u{11A9A}-\u{11A9C}\u{11A9E}-\u{11AA2}\u{11AC0}-\u{11AF8}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2F}\u{11C3E}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11CA9}\u{11CB1}\u{11CB4}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D50}-\u{11D59}\u{12000}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{13000}-\u{1342E}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}\u{16A6F}\u{16AD0}-\u{16AED}\u{16AF5}\u{16B00}-\u{16B2F}\u{16B37}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16F00}-\u{16F44}\u{16F50}-\u{16F7E}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{17000}-\u{187EC}\u{18800}-\u{18AF2}\u{1B000}-\u{1B11E}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}\u{1BC9F}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D166}\u{1D16A}-\u{1D172}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D360}-\u{1D371}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6DA}\u{1D6DC}-\u{1D714}\u{1D716}-\u{1D74E}\u{1D750}-\u{1D788}\u{1D78A}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1D7CE}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}-\u{1DA8B}\u{1F100}-\u{1F10A}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F169}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{20000}-\u{2A6D6}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}][\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111CA}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]*$/u; + +var regexes = { + combiningMarks, + combiningClassVirama, + validZWNJ, + bidiDomain, + bidiS1LTR, + bidiS1RTL, + bidiS2, + bidiS3, + bidiS4EN, + bidiS4AN, + bidiS5, + bidiS6 +}; + + + +var mappingTable = /*#__PURE__*/Object.freeze({ + __proto__: null +}); + +var mappingTable$1 = getCjsExportFromNamespace(mappingTable); + +function containsNonASCII(str) { + return /[^\x00-\x7F]/.test(str); +} + +function findStatus(val, { useSTD3ASCIIRules }) { + let start = 0; + let end = mappingTable$1.length - 1; + + while (start <= end) { + const mid = Math.floor((start + end) / 2); + + const target = mappingTable$1[mid]; + if (target[0][0] <= val && target[0][1] >= val) { + if (target[1].startsWith("disallowed_STD3_")) { + const newStatus = useSTD3ASCIIRules ? "disallowed" : target[1].slice(16); + return [newStatus, ...target.slice(2)]; + } + return target.slice(1); + } else if (target[0][0] > val) { + end = mid - 1; + } else { + start = mid + 1; + } + } + + return null; +} + +function mapChars(domainName, { useSTD3ASCIIRules, processingOption }) { + let hasError = false; + let processed = ""; + + for (const ch of domainName) { + const [status, mapping] = findStatus(ch.codePointAt(0), { useSTD3ASCIIRules }); + + switch (status) { + case "disallowed": + hasError = true; + processed += ch; + break; + case "ignored": + break; + case "mapped": + processed += mapping; + break; + case "deviation": + if (processingOption === "transitional") { + processed += mapping; + } else { + processed += ch; + } + break; + case "valid": + processed += ch; + break; + } + } + + return { + string: processed, + error: hasError + }; +} + +function validateLabel(label, { checkHyphens, checkBidi, checkJoiners, processingOption, useSTD3ASCIIRules }) { + if (label.normalize("NFC") !== label) { + return false; + } + + const codePoints = Array.from(label); + + if (checkHyphens) { + if ((codePoints[2] === "-" && codePoints[3] === "-") || + (label.startsWith("-") || label.endsWith("-"))) { + return false; + } + } + + if (label.includes(".") || + (codePoints.length > 0 && regexes.combiningMarks.test(codePoints[0]))) { + return false; + } + + for (const ch of codePoints) { + const [status] = findStatus(ch.codePointAt(0), { useSTD3ASCIIRules }); + if ((processingOption === "transitional" && status !== "valid") || + (processingOption === "nontransitional" && + status !== "valid" && status !== "deviation")) { + return false; + } + } + + // https://tools.ietf.org/html/rfc5892#appendix-A + if (checkJoiners) { + let last = 0; + for (const [i, ch] of codePoints.entries()) { + if (ch === "\u200C" || ch === "\u200D") { + if (i > 0) { + if (regexes.combiningClassVirama.test(codePoints[i - 1])) { + continue; + } + if (ch === "\u200C") { + // TODO: make this more efficient + const next = codePoints.indexOf("\u200C", i + 1); + const test = next < 0 ? codePoints.slice(last) : codePoints.slice(last, next); + if (regexes.validZWNJ.test(test.join(""))) { + last = i + 1; + continue; + } + } + } + return false; + } + } + } + + // https://tools.ietf.org/html/rfc5893#section-2 + if (checkBidi) { + let rtl; + + // 1 + if (regexes.bidiS1LTR.test(codePoints[0])) { + rtl = false; + } else if (regexes.bidiS1RTL.test(codePoints[0])) { + rtl = true; + } else { + return false; + } + + if (rtl) { + // 2-4 + if (!regexes.bidiS2.test(label) || + !regexes.bidiS3.test(label) || + (regexes.bidiS4EN.test(label) && regexes.bidiS4AN.test(label))) { + return false; + } + } else if (!regexes.bidiS5.test(label) || + !regexes.bidiS6.test(label)) { // 5-6 + return false; + } + } + + return true; +} + +function isBidiDomain(labels) { + const domain = labels.map(label => { + if (label.startsWith("xn--")) { + try { + return punycode.decode(label.substring(4)); + } catch (err) { + return ""; + } + } + return label; + }).join("."); + return regexes.bidiDomain.test(domain); +} + +function processing(domainName, options) { + const { processingOption } = options; + + // 1. Map. + let { string, error } = mapChars(domainName, options); + + // 2. Normalize. + string = string.normalize("NFC"); + + // 3. Break. + const labels = string.split("."); + const isBidi = isBidiDomain(labels); + + // 4. Convert/Validate. + for (const [i, origLabel] of labels.entries()) { + let label = origLabel; + let curProcessing = processingOption; + if (label.startsWith("xn--")) { + try { + label = punycode.decode(label.substring(4)); + labels[i] = label; + } catch (err) { + error = true; + continue; + } + curProcessing = "nontransitional"; + } + + // No need to validate if we already know there is an error. + if (error) { + continue; + } + const validation = validateLabel(label, Object.assign({}, options, { + processingOption: curProcessing, + checkBidi: options.checkBidi && isBidi + })); + if (!validation) { + error = true; + } + } + + return { + string: labels.join("."), + error + }; +} + +function toASCII$1(domainName, { + checkHyphens = false, + checkBidi = false, + checkJoiners = false, + useSTD3ASCIIRules = false, + processingOption = "nontransitional", + verifyDNSLength = false +} = {}) { + if (processingOption !== "transitional" && processingOption !== "nontransitional") { + throw new RangeError("processingOption must be either transitional or nontransitional"); + } + + const result = processing(domainName, { + processingOption, + checkHyphens, + checkBidi, + checkJoiners, + useSTD3ASCIIRules + }); + let labels = result.string.split("."); + labels = labels.map(l => { + if (containsNonASCII(l)) { + try { + return "xn--" + punycode.encode(l); + } catch (e) { + result.error = true; + } + } + return l; + }); + + if (verifyDNSLength) { + const total = labels.join(".").length; + if (total > 253 || total === 0) { + result.error = true; + } + + for (let i = 0; i < labels.length; ++i) { + if (labels[i].length > 63 || labels[i].length === 0) { + result.error = true; + break; + } + } + } + + if (result.error) { + return null; + } + return labels.join("."); +} + +function toUnicode$1(domainName, { + checkHyphens = false, + checkBidi = false, + checkJoiners = false, + useSTD3ASCIIRules = false +} = {}) { + const result = processing(domainName, { + processingOption: "nontransitional", + checkHyphens, + checkBidi, + checkJoiners, + useSTD3ASCIIRules + }); + + return { + domain: result.string, + error: result.error + }; +} + +var tr46 = { + toASCII: toASCII$1, + toUnicode: toUnicode$1 +}; + +function isASCIIDigit(c) { + return c >= 0x30 && c <= 0x39; +} + +function isASCIIAlpha(c) { + return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); +} + +function isASCIIAlphanumeric(c) { + return isASCIIAlpha(c) || isASCIIDigit(c); +} + +function isASCIIHex(c) { + return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); +} + +var infra = { + isASCIIDigit, + isASCIIAlpha, + isASCIIAlphanumeric, + isASCIIHex +}; + +const { isASCIIHex: isASCIIHex$1 } = infra; + +function strictlySplitByteSequence(buf, cp) { + const list = []; + let last = 0; + let i = buf.indexOf(cp); + while (i >= 0) { + list.push(buf.slice(last, i)); + last = i + 1; + i = buf.indexOf(cp, last); + } + if (last !== buf.length) { + list.push(buf.slice(last)); + } + return list; +} + +function replaceByteInByteSequence(buf, from, to) { + let i = buf.indexOf(from); + while (i >= 0) { + buf[i] = to; + i = buf.indexOf(from, i + 1); + } + return buf; +} + +function percentEncode(c) { + let hex = c.toString(16).toUpperCase(); + if (hex.length === 1) { + hex = "0" + hex; + } + + return "%" + hex; +} + +function percentDecode(input) { + const output = Buffer$1.alloc(input.byteLength); + let ptr = 0; + for (let i = 0; i < input.length; ++i) { + if (input[i] !== 37 || !isASCIIHex$1(input[i + 1]) || !isASCIIHex$1(input[i + 2])) { + output[ptr++] = input[i]; + } else { + output[ptr++] = parseInt(input.slice(i + 1, i + 3).toString(), 16); + i += 2; + } + } + return output.slice(0, ptr); +} + +function parseUrlencoded(input) { + const sequences = strictlySplitByteSequence(input, 38); + const output = []; + for (const bytes of sequences) { + if (bytes.length === 0) { + continue; + } + + let name; + let value; + const indexOfEqual = bytes.indexOf(61); + + if (indexOfEqual >= 0) { + name = bytes.slice(0, indexOfEqual); + value = bytes.slice(indexOfEqual + 1); + } else { + name = bytes; + value = Buffer$1.alloc(0); + } + + name = replaceByteInByteSequence(Buffer$1.from(name), 43, 32); + value = replaceByteInByteSequence(Buffer$1.from(value), 43, 32); + + output.push([percentDecode(name).toString(), percentDecode(value).toString()]); + } + return output; +} + +function serializeUrlencodedByte(input) { + let output = ""; + for (const byte of input) { + if (byte === 32) { + output += "+"; + } else if (byte === 42 || + byte === 45 || + byte === 46 || + (byte >= 48 && byte <= 57) || + (byte >= 65 && byte <= 90) || + byte === 95 || + (byte >= 97 && byte <= 122)) { + output += String.fromCodePoint(byte); + } else { + output += percentEncode(byte); + } + } + return output; +} + +function serializeUrlencoded(tuples, encodingOverride = undefined) { + let encoding = "utf-8"; + if (encodingOverride !== undefined) { + encoding = encodingOverride; + } + + let output = ""; + for (const [i, tuple] of tuples.entries()) { + // TODO: handle encoding override + const name = serializeUrlencodedByte(Buffer$1.from(tuple[0])); + let value = tuple[1]; + if (tuple.length > 2 && tuple[2] !== undefined) { + if (tuple[2] === "hidden" && name === "_charset_") { + value = encoding; + } else if (tuple[2] === "file") { + // value is a File object + value = value.name; + } + } + value = serializeUrlencodedByte(Buffer$1.from(value)); + if (i !== 0) { + output += "&"; + } + output += `${name}=${value}`; + } + return output; +} + +var urlencoded = { + percentEncode, + percentDecode, + + // application/x-www-form-urlencoded string parser + parseUrlencoded(input) { + return parseUrlencoded(Buffer$1.from(input)); + }, + + // application/x-www-form-urlencoded serializer + serializeUrlencoded +}; + +var urlStateMachine = createCommonjsModule(function (module) { + + + + +const { percentEncode, percentDecode } = urlencoded; + +const specialSchemes = { + ftp: 21, + file: null, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443 +}; + +const failure = Symbol("failure"); + +function countSymbols(str) { + return punycode.ucs2.decode(str).length; +} + +function at(input, idx) { + const c = input[idx]; + return isNaN(c) ? undefined : String.fromCodePoint(c); +} + +function isSingleDot(buffer) { + return buffer === "." || buffer.toLowerCase() === "%2e"; +} + +function isDoubleDot(buffer) { + buffer = buffer.toLowerCase(); + return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; +} + +function isWindowsDriveLetterCodePoints(cp1, cp2) { + return infra.isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); +} + +function isWindowsDriveLetterString(string) { + return string.length === 2 && infra.isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); +} + +function isNormalizedWindowsDriveLetterString(string) { + return string.length === 2 && infra.isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; +} + +function containsForbiddenHostCodePoint(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function containsForbiddenHostCodePointExcludingPercent(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function isSpecialScheme(scheme) { + return specialSchemes[scheme] !== undefined; +} + +function isSpecial(url) { + return isSpecialScheme(url.scheme); +} + +function isNotSpecial(url) { + return !isSpecialScheme(url.scheme); +} + +function defaultPort(scheme) { + return specialSchemes[scheme]; +} + +function utf8PercentEncode(c) { + const buf = Buffer$1.from(c); + + let str = ""; + + for (let i = 0; i < buf.length; ++i) { + str += percentEncode(buf[i]); + } + + return str; +} + +function isC0ControlPercentEncode(c) { + return c <= 0x1F || c > 0x7E; +} + +const extraUserinfoPercentEncodeSet = + new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); +function isUserinfoPercentEncode(c) { + return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); +} + +const extraFragmentPercentEncodeSet = new Set([32, 34, 60, 62, 96]); +function isFragmentPercentEncode(c) { + return isC0ControlPercentEncode(c) || extraFragmentPercentEncodeSet.has(c); +} + +const extraPathPercentEncodeSet = new Set([35, 63, 123, 125]); +function isPathPercentEncode(c) { + return isFragmentPercentEncode(c) || extraPathPercentEncodeSet.has(c); +} + +function percentEncodeChar(c, encodeSetPredicate) { + const cStr = String.fromCodePoint(c); + + if (encodeSetPredicate(c)) { + return utf8PercentEncode(cStr); + } + + return cStr; +} + +function parseIPv4Number(input) { + let R = 10; + + if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { + input = input.substring(2); + R = 16; + } else if (input.length >= 2 && input.charAt(0) === "0") { + input = input.substring(1); + R = 8; + } + + if (input === "") { + return 0; + } + + let regex = /[^0-7]/; + if (R === 10) { + regex = /[^0-9]/; + } + if (R === 16) { + regex = /[^0-9A-Fa-f]/; + } + + if (regex.test(input)) { + return failure; + } + + return parseInt(input, R); +} + +function parseIPv4(input) { + const parts = input.split("."); + if (parts[parts.length - 1] === "") { + if (parts.length > 1) { + parts.pop(); + } + } + + if (parts.length > 4) { + return input; + } + + const numbers = []; + for (const part of parts) { + if (part === "") { + return input; + } + const n = parseIPv4Number(part); + if (n === failure) { + return input; + } + + numbers.push(n); + } + + for (let i = 0; i < numbers.length - 1; ++i) { + if (numbers[i] > 255) { + return failure; + } + } + if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { + return failure; + } + + let ipv4 = numbers.pop(); + let counter = 0; + + for (const n of numbers) { + ipv4 += n * Math.pow(256, 3 - counter); + ++counter; + } + + return ipv4; +} + +function serializeIPv4(address) { + let output = ""; + let n = address; + + for (let i = 1; i <= 4; ++i) { + output = String(n % 256) + output; + if (i !== 4) { + output = "." + output; + } + n = Math.floor(n / 256); + } + + return output; +} + +function parseIPv6(input) { + const address = [0, 0, 0, 0, 0, 0, 0, 0]; + let pieceIndex = 0; + let compress = null; + let pointer = 0; + + input = punycode.ucs2.decode(input); + + if (input[pointer] === 58) { + if (input[pointer + 1] !== 58) { + return failure; + } + + pointer += 2; + ++pieceIndex; + compress = pieceIndex; + } + + while (pointer < input.length) { + if (pieceIndex === 8) { + return failure; + } + + if (input[pointer] === 58) { + if (compress !== null) { + return failure; + } + ++pointer; + ++pieceIndex; + compress = pieceIndex; + continue; + } + + let value = 0; + let length = 0; + + while (length < 4 && infra.isASCIIHex(input[pointer])) { + value = value * 0x10 + parseInt(at(input, pointer), 16); + ++pointer; + ++length; + } + + if (input[pointer] === 46) { + if (length === 0) { + return failure; + } + + pointer -= length; + + if (pieceIndex > 6) { + return failure; + } + + let numbersSeen = 0; + + while (input[pointer] !== undefined) { + let ipv4Piece = null; + + if (numbersSeen > 0) { + if (input[pointer] === 46 && numbersSeen < 4) { + ++pointer; + } else { + return failure; + } + } + + if (!infra.isASCIIDigit(input[pointer])) { + return failure; + } + + while (infra.isASCIIDigit(input[pointer])) { + const number = parseInt(at(input, pointer)); + if (ipv4Piece === null) { + ipv4Piece = number; + } else if (ipv4Piece === 0) { + return failure; + } else { + ipv4Piece = ipv4Piece * 10 + number; + } + if (ipv4Piece > 255) { + return failure; + } + ++pointer; + } + + address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; + + ++numbersSeen; + + if (numbersSeen === 2 || numbersSeen === 4) { + ++pieceIndex; + } + } + + if (numbersSeen !== 4) { + return failure; + } + + break; + } else if (input[pointer] === 58) { + ++pointer; + if (input[pointer] === undefined) { + return failure; + } + } else if (input[pointer] !== undefined) { + return failure; + } + + address[pieceIndex] = value; + ++pieceIndex; + } + + if (compress !== null) { + let swaps = pieceIndex - compress; + pieceIndex = 7; + while (pieceIndex !== 0 && swaps > 0) { + const temp = address[compress + swaps - 1]; + address[compress + swaps - 1] = address[pieceIndex]; + address[pieceIndex] = temp; + --pieceIndex; + --swaps; + } + } else if (compress === null && pieceIndex !== 8) { + return failure; + } + + return address; +} + +function serializeIPv6(address) { + let output = ""; + const seqResult = findLongestZeroSequence(address); + const compress = seqResult.idx; + let ignore0 = false; + + for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { + if (ignore0 && address[pieceIndex] === 0) { + continue; + } else if (ignore0) { + ignore0 = false; + } + + if (compress === pieceIndex) { + const separator = pieceIndex === 0 ? "::" : ":"; + output += separator; + ignore0 = true; + continue; + } + + output += address[pieceIndex].toString(16); + + if (pieceIndex !== 7) { + output += ":"; + } + } + + return output; +} + +function parseHost(input, isNotSpecialArg = false) { + if (input[0] === "[") { + if (input[input.length - 1] !== "]") { + return failure; + } + + return parseIPv6(input.substring(1, input.length - 1)); + } + + if (isNotSpecialArg) { + return parseOpaqueHost(input); + } + + const domain = percentDecode(Buffer$1.from(input)).toString(); + const asciiDomain = domainToASCII(domain); + if (asciiDomain === failure) { + return failure; + } + + if (containsForbiddenHostCodePoint(asciiDomain)) { + return failure; + } + + const ipv4Host = parseIPv4(asciiDomain); + if (typeof ipv4Host === "number" || ipv4Host === failure) { + return ipv4Host; + } + + return asciiDomain; +} + +function parseOpaqueHost(input) { + if (containsForbiddenHostCodePointExcludingPercent(input)) { + return failure; + } + + let output = ""; + const decoded = punycode.ucs2.decode(input); + for (let i = 0; i < decoded.length; ++i) { + output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); + } + return output; +} + +function findLongestZeroSequence(arr) { + let maxIdx = null; + let maxLen = 1; // only find elements > 1 + let currStart = null; + let currLen = 0; + + for (let i = 0; i < arr.length; ++i) { + if (arr[i] !== 0) { + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + currStart = null; + currLen = 0; + } else { + if (currStart === null) { + currStart = i; + } + ++currLen; + } + } + + // if trailing zeros + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + return { + idx: maxIdx, + len: maxLen + }; +} + +function serializeHost(host) { + if (typeof host === "number") { + return serializeIPv4(host); + } + + // IPv6 serializer + if (host instanceof Array) { + return "[" + serializeIPv6(host) + "]"; + } + + return host; +} + +function domainToASCII(domain, beStrict = false) { + const result = tr46.toASCII(domain, { + checkBidi: true, + checkHyphens: false, + checkJoiners: true, + useSTD3ASCIIRules: beStrict, + verifyDNSLength: beStrict + }); + if (result === null) { + return failure; + } + return result; +} + +function trimControlChars(url) { + return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); +} + +function trimTabAndNewline(url) { + return url.replace(/\u0009|\u000A|\u000D/g, ""); +} + +function shortenPath(url) { + const { path } = url; + if (path.length === 0) { + return; + } + if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { + return; + } + + path.pop(); +} + +function includesCredentials(url) { + return url.username !== "" || url.password !== ""; +} + +function cannotHaveAUsernamePasswordPort(url) { + return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; +} + +function isNormalizedWindowsDriveLetter(string) { + return /^[A-Za-z]:$/.test(string); +} + +function URLStateMachine(input, base, encodingOverride, url, stateOverride) { + this.pointer = 0; + this.input = input; + this.base = base || null; + this.encodingOverride = encodingOverride || "utf-8"; + this.stateOverride = stateOverride; + this.url = url; + this.failure = false; + this.parseError = false; + + if (!this.url) { + this.url = { + scheme: "", + username: "", + password: "", + host: null, + port: null, + path: [], + query: null, + fragment: null, + + cannotBeABaseURL: false + }; + + const res = trimControlChars(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + } + + const res = trimTabAndNewline(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + + this.state = stateOverride || "scheme start"; + + this.buffer = ""; + this.atFlag = false; + this.arrFlag = false; + this.passwordTokenSeenFlag = false; + + this.input = punycode.ucs2.decode(this.input); + + for (; this.pointer <= this.input.length; ++this.pointer) { + const c = this.input[this.pointer]; + const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); + + // exec state machine + const ret = this["parse " + this.state](c, cStr); + if (!ret) { + break; // terminate algorithm + } else if (ret === failure) { + this.failure = true; + break; + } + } +} + +URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { + if (infra.isASCIIAlpha(c)) { + this.buffer += cStr.toLowerCase(); + this.state = "scheme"; + } else if (!this.stateOverride) { + this.state = "no scheme"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { + if (infra.isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { + this.buffer += cStr.toLowerCase(); + } else if (c === 58) { + if (this.stateOverride) { + if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { + return false; + } + + if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { + return false; + } + + if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { + return false; + } + + if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { + return false; + } + } + this.url.scheme = this.buffer; + if (this.stateOverride) { + if (this.url.port === defaultPort(this.url.scheme)) { + this.url.port = null; + } + return false; + } + this.buffer = ""; + if (this.url.scheme === "file") { + if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { + this.parseError = true; + } + this.state = "file"; + } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { + this.state = "special relative or authority"; + } else if (isSpecial(this.url)) { + this.state = "special authority slashes"; + } else if (this.input[this.pointer + 1] === 47) { + this.state = "path or authority"; + ++this.pointer; + } else { + this.url.cannotBeABaseURL = true; + this.url.path.push(""); + this.state = "cannot-be-a-base-URL path"; + } + } else if (!this.stateOverride) { + this.buffer = ""; + this.state = "no scheme"; + this.pointer = -1; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { + if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { + return failure; + } else if (this.base.cannotBeABaseURL && c === 35) { + this.url.scheme = this.base.scheme; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.url.cannotBeABaseURL = true; + this.state = "fragment"; + } else if (this.base.scheme === "file") { + this.state = "file"; + --this.pointer; + } else { + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { + if (c === 47) { + this.state = "authority"; + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative"] = function parseRelative(c) { + this.url.scheme = this.base.scheme; + if (isNaN(c)) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 47) { + this.state = "relative slash"; + } else if (c === 63) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else if (isSpecial(this.url) && c === 92) { + this.parseError = true; + this.state = "relative slash"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(0, this.base.path.length - 1); + + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { + if (isSpecial(this.url) && (c === 47 || c === 92)) { + if (c === 92) { + this.parseError = true; + } + this.state = "special authority ignore slashes"; + } else if (c === 47) { + this.state = "authority"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "special authority ignore slashes"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { + if (c !== 47 && c !== 92) { + this.state = "authority"; + --this.pointer; + } else { + this.parseError = true; + } + + return true; +}; + +URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { + if (c === 64) { + this.parseError = true; + if (this.atFlag) { + this.buffer = "%40" + this.buffer; + } + this.atFlag = true; + + // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars + const len = countSymbols(this.buffer); + for (let pointer = 0; pointer < len; ++pointer) { + const codePoint = this.buffer.codePointAt(pointer); + + if (codePoint === 58 && !this.passwordTokenSeenFlag) { + this.passwordTokenSeenFlag = true; + continue; + } + const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); + if (this.passwordTokenSeenFlag) { + this.url.password += encodedCodePoints; + } else { + this.url.username += encodedCodePoints; + } + } + this.buffer = ""; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + if (this.atFlag && this.buffer === "") { + this.parseError = true; + return failure; + } + this.pointer -= countSymbols(this.buffer) + 1; + this.buffer = ""; + this.state = "host"; + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse hostname"] = +URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { + if (this.stateOverride && this.url.scheme === "file") { + --this.pointer; + this.state = "file host"; + } else if (c === 58 && !this.arrFlag) { + if (this.buffer === "") { + this.parseError = true; + return failure; + } + + const host = parseHost(this.buffer, isNotSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "port"; + if (this.stateOverride === "hostname") { + return false; + } + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + --this.pointer; + if (isSpecial(this.url) && this.buffer === "") { + this.parseError = true; + return failure; + } else if (this.stateOverride && this.buffer === "" && + (includesCredentials(this.url) || this.url.port !== null)) { + this.parseError = true; + return false; + } + + const host = parseHost(this.buffer, isNotSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "path start"; + if (this.stateOverride) { + return false; + } + } else { + if (c === 91) { + this.arrFlag = true; + } else if (c === 93) { + this.arrFlag = false; + } + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { + if (infra.isASCIIDigit(c)) { + this.buffer += cStr; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92) || + this.stateOverride) { + if (this.buffer !== "") { + const port = parseInt(this.buffer); + if (port > Math.pow(2, 16) - 1) { + this.parseError = true; + return failure; + } + this.url.port = port === defaultPort(this.url.scheme) ? null : port; + this.buffer = ""; + } + if (this.stateOverride) { + return false; + } + this.state = "path start"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); + +function startsWithWindowsDriveLetter(input, pointer) { + const length = input.length - pointer; + return length >= 2 && + isWindowsDriveLetterCodePoints(input[pointer], input[pointer + 1]) && + (length === 2 || fileOtherwiseCodePoints.has(input[pointer + 2])); +} + +URLStateMachine.prototype["parse file"] = function parseFile(c) { + this.url.scheme = "file"; + + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file slash"; + } else if (this.base !== null && this.base.scheme === "file") { + if (isNaN(c)) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 63) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else { + if (!startsWithWindowsDriveLetter(this.input, this.pointer)) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + shortenPath(this.url); + } else { + this.parseError = true; + } + + this.state = "path"; + --this.pointer; + } + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file host"; + } else { + if (this.base !== null && this.base.scheme === "file" && + !startsWithWindowsDriveLetter(this.input, this.pointer)) { + if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { + this.url.path.push(this.base.path[0]); + } else { + this.url.host = this.base.host; + } + } + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { + if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { + --this.pointer; + if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { + this.parseError = true; + this.state = "path"; + } else if (this.buffer === "") { + this.url.host = ""; + if (this.stateOverride) { + return false; + } + this.state = "path start"; + } else { + let host = parseHost(this.buffer, isNotSpecial(this.url)); + if (host === failure) { + return failure; + } + if (host === "localhost") { + host = ""; + } + this.url.host = host; + + if (this.stateOverride) { + return false; + } + + this.buffer = ""; + this.state = "path start"; + } + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { + if (isSpecial(this.url)) { + if (c === 92) { + this.parseError = true; + } + this.state = "path"; + + if (c !== 47 && c !== 92) { + --this.pointer; + } + } else if (!this.stateOverride && c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (!this.stateOverride && c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (c !== undefined) { + this.state = "path"; + if (c !== 47) { + --this.pointer; + } + } + + return true; +}; + +URLStateMachine.prototype["parse path"] = function parsePath(c) { + if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || + (!this.stateOverride && (c === 63 || c === 35))) { + if (isSpecial(this.url) && c === 92) { + this.parseError = true; + } + + if (isDoubleDot(this.buffer)) { + shortenPath(this.url); + if (c !== 47 && !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } + } else if (isSingleDot(this.buffer) && c !== 47 && + !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } else if (!isSingleDot(this.buffer)) { + if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { + if (this.url.host !== "" && this.url.host !== null) { + this.parseError = true; + this.url.host = ""; + } + this.buffer = this.buffer[0] + ":"; + } + this.url.path.push(this.buffer); + } + this.buffer = ""; + if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { + while (this.url.path.length > 1 && this.url.path[0] === "") { + this.parseError = true; + this.url.path.shift(); + } + } + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + + if (c === 37 && + (!infra.isASCIIHex(this.input[this.pointer + 1]) || + !infra.isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += percentEncodeChar(c, isPathPercentEncode); + } + + return true; +}; + +URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else { + // TODO: Add: not a URL code point + if (!isNaN(c) && c !== 37) { + this.parseError = true; + } + + if (c === 37 && + (!infra.isASCIIHex(this.input[this.pointer + 1]) || + !infra.isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + if (!isNaN(c)) { + this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); + } + } + + return true; +}; + +URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { + if (isNaN(c) || (!this.stateOverride && c === 35)) { + if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { + this.encodingOverride = "utf-8"; + } + + const buffer = Buffer$1.from(this.buffer); // TODO: Use encoding override instead + for (let i = 0; i < buffer.length; ++i) { + if (buffer[i] < 0x21 || + buffer[i] > 0x7E || + buffer[i] === 0x22 || buffer[i] === 0x23 || buffer[i] === 0x3C || buffer[i] === 0x3E || + (buffer[i] === 0x27 && isSpecial(this.url))) { + this.url.query += percentEncode(buffer[i]); + } else { + this.url.query += String.fromCodePoint(buffer[i]); + } + } + + this.buffer = ""; + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!infra.isASCIIHex(this.input[this.pointer + 1]) || + !infra.isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { + if (isNaN(c)) ; else if (c === 0x0) { + this.parseError = true; + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!infra.isASCIIHex(this.input[this.pointer + 1]) || + !infra.isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.url.fragment += percentEncodeChar(c, isFragmentPercentEncode); + } + + return true; +}; + +function serializeURL(url, excludeFragment) { + let output = url.scheme + ":"; + if (url.host !== null) { + output += "//"; + + if (url.username !== "" || url.password !== "") { + output += url.username; + if (url.password !== "") { + output += ":" + url.password; + } + output += "@"; + } + + output += serializeHost(url.host); + + if (url.port !== null) { + output += ":" + url.port; + } + } else if (url.host === null && url.scheme === "file") { + output += "//"; + } + + if (url.cannotBeABaseURL) { + output += url.path[0]; + } else { + for (const string of url.path) { + output += "/" + string; + } + } + + if (url.query !== null) { + output += "?" + url.query; + } + + if (!excludeFragment && url.fragment !== null) { + output += "#" + url.fragment; + } + + return output; +} + +function serializeOrigin(tuple) { + let result = tuple.scheme + "://"; + result += serializeHost(tuple.host); + + if (tuple.port !== null) { + result += ":" + tuple.port; + } + + return result; +} + +module.exports.serializeURL = serializeURL; + +module.exports.serializeURLOrigin = function (url) { + // https://url.spec.whatwg.org/#concept-url-origin + switch (url.scheme) { + case "blob": + try { + return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); + } catch (e) { + // serializing an opaque origin returns "null" + return "null"; + } + case "ftp": + case "gopher": + case "http": + case "https": + case "ws": + case "wss": + return serializeOrigin({ + scheme: url.scheme, + host: url.host, + port: url.port + }); + case "file": + // spec says "exercise to the reader", chrome says "file://" + return "file://"; + default: + // serializing an opaque origin returns "null" + return "null"; + } +}; + +module.exports.basicURLParse = function (input, options) { + if (options === undefined) { + options = {}; + } + + const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); + if (usm.failure) { + return null; + } + + return usm.url; +}; + +module.exports.setTheUsername = function (url, username) { + url.username = ""; + const decoded = punycode.ucs2.decode(username); + for (let i = 0; i < decoded.length; ++i) { + url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.setThePassword = function (url, password) { + url.password = ""; + const decoded = punycode.ucs2.decode(password); + for (let i = 0; i < decoded.length; ++i) { + url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.serializeHost = serializeHost; + +module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; + +module.exports.serializeInteger = function (integer) { + return String(integer); +}; + +module.exports.parseURL = function (input, options) { + if (options === undefined) { + options = {}; + } + + // We don't handle blobs, so this just delegates: + return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); +}; +}); +var urlStateMachine_1 = urlStateMachine.serializeURL; +var urlStateMachine_2 = urlStateMachine.serializeURLOrigin; +var urlStateMachine_3 = urlStateMachine.basicURLParse; +var urlStateMachine_4 = urlStateMachine.setTheUsername; +var urlStateMachine_5 = urlStateMachine.setThePassword; +var urlStateMachine_6 = urlStateMachine.serializeHost; +var urlStateMachine_7 = urlStateMachine.cannotHaveAUsernamePasswordPort; +var urlStateMachine_8 = urlStateMachine.serializeInteger; +var urlStateMachine_9 = urlStateMachine.parseURL; + +var lodash_sortby = createCommonjsModule(function (module, exports) { +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; + +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; + +/** Used to compose bitmasks for comparison styles. */ +var UNORDERED_COMPARE_FLAG = 1, + PARTIAL_COMPARE_FLAG = 2; + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991; + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + weakMapTag = '[object WeakMap]'; + +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + +/** Used to match property names within property paths. */ +var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + reLeadingDot = /^\./, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + +/** Used to match backslashes in property paths. */ +var reEscapeChar = /\\(\\)?/g; + +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** Used to identify `toStringTag` values of typed arrays. */ +var typedArrayTags = {}; +typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = +typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = +typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = +typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = +typedArrayTags[uint32Tag] = true; +typedArrayTags[argsTag] = typedArrayTags[arrayTag] = +typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = +typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = +typedArrayTags[errorTag] = typedArrayTags[funcTag] = +typedArrayTags[mapTag] = typedArrayTags[numberTag] = +typedArrayTags[objectTag] = typedArrayTags[regexpTag] = +typedArrayTags[setTag] = typedArrayTags[stringTag] = +typedArrayTags[weakMapTag] = false; + +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); + +/** Detect free variable `exports`. */ +var freeExports = exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; + +/** Detect free variable `process` from Node.js. */ +var freeProcess = moduleExports && freeGlobal.process; + +/** Used to access faster Node.js helpers. */ +var nodeUtil = (function() { + try { + return freeProcess && freeProcess.binding('util'); + } catch (e) {} +}()); + +/* Node.js helper references. */ +var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + +/** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ +function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); +} + +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function arrayMap(array, iteratee) { + var index = -1, + length = array ? array.length : 0, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; +} + +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; +} + +/** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ +function arraySome(array, predicate) { + var index = -1, + length = array ? array.length : 0; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; +} + +/** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ +function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; +} + +/** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ +function baseSortBy(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; +} + +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +/** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ +function baseUnary(func) { + return function(value) { + return func(value); + }; +} + +/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function getValue(object, key) { + return object == null ? undefined : object[key]; +} + +/** + * Checks if `value` is a host object in IE < 9. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a host object, else `false`. + */ +function isHostObject(value) { + // Many host objects are `Object` objects that can coerce to strings + // despite having improperly defined `toString` methods. + var result = false; + if (value != null && typeof value.toString != 'function') { + try { + result = !!(value + ''); + } catch (e) {} + } + return result; +} + +/** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ +function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; +} + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +/** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ +function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; +} + +/** Used for built-in method references. */ +var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + +/** Used to detect overreaching core-js shims. */ +var coreJsData = root['__core-js_shared__']; + +/** Used to detect methods masquerading as native. */ +var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; +}()); + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); + +/** Built-in value references. */ +var Symbol = root.Symbol, + Uint8Array = root.Uint8Array, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max; + +/* Built-in method references that are verified to be native. */ +var DataView = getNative(root, 'DataView'), + Map = getNative(root, 'Map'), + Promise = getNative(root, 'Promise'), + Set = getNative(root, 'Set'), + WeakMap = getNative(root, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); + +/** Used to detect maps, sets, and weakmaps. */ +var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Hash(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ +function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; +} + +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(key) { + return this.has(key) && delete this.__data__[key]; +} + +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; +} + +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function hashHas(key) { + var data = this.__data__; + return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); +} + +/** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ +function hashSet(key, value) { + var data = this.__data__; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; +} + +// Add methods to `Hash`. +Hash.prototype.clear = hashClear; +Hash.prototype['delete'] = hashDelete; +Hash.prototype.get = hashGet; +Hash.prototype.has = hashHas; +Hash.prototype.set = hashSet; + +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function ListCache(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; +} + +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + return true; +} + +/** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; +} + +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; +} + +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ +function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; +} + +// Add methods to `ListCache`. +ListCache.prototype.clear = listCacheClear; +ListCache.prototype['delete'] = listCacheDelete; +ListCache.prototype.get = listCacheGet; +ListCache.prototype.has = listCacheHas; +ListCache.prototype.set = listCacheSet; + +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function MapCache(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ +function mapCacheClear() { + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; +} + +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function mapCacheDelete(key) { + return getMapData(this, key)['delete'](key); +} + +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function mapCacheGet(key) { + return getMapData(this, key).get(key); +} + +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function mapCacheHas(key) { + return getMapData(this, key).has(key); +} + +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ +function mapCacheSet(key, value) { + getMapData(this, key).set(key, value); + return this; +} + +// Add methods to `MapCache`. +MapCache.prototype.clear = mapCacheClear; +MapCache.prototype['delete'] = mapCacheDelete; +MapCache.prototype.get = mapCacheGet; +MapCache.prototype.has = mapCacheHas; +MapCache.prototype.set = mapCacheSet; + +/** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ +function SetCache(values) { + var index = -1, + length = values ? values.length : 0; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } +} + +/** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ +function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; +} + +/** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ +function setCacheHas(value) { + return this.__data__.has(value); +} + +// Add methods to `SetCache`. +SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; +SetCache.prototype.has = setCacheHas; + +/** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Stack(entries) { + this.__data__ = new ListCache(entries); +} + +/** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ +function stackClear() { + this.__data__ = new ListCache; +} + +/** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function stackDelete(key) { + return this.__data__['delete'](key); +} + +/** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function stackGet(key) { + return this.__data__.get(key); +} + +/** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function stackHas(key) { + return this.__data__.has(key); +} + +/** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ +function stackSet(key, value) { + var cache = this.__data__; + if (cache instanceof ListCache) { + var pairs = cache.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + return this; + } + cache = this.__data__ = new MapCache(pairs); + } + cache.set(key, value); + return this; +} + +// Add methods to `Stack`. +Stack.prototype.clear = stackClear; +Stack.prototype['delete'] = stackDelete; +Stack.prototype.get = stackGet; +Stack.prototype.has = stackHas; +Stack.prototype.set = stackSet; + +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + // Safari 9 makes `arguments.length` enumerable in strict mode. + var result = (isArray(value) || isArguments(value)) + ? baseTimes(value.length, String) + : []; + + var length = result.length, + skipIndexes = !!length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && (key == 'length' || isIndex(key, length)))) { + result.push(key); + } + } + return result; +} + +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; +} + +/** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ +var baseEach = createBaseEach(baseForOwn); + +/** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ +function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; +} + +/** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ +var baseFor = createBaseFor(); + +/** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ +function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); +} + +/** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ +function baseGet(object, path) { + path = isKey(path, object) ? [path] : castPath(path); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; +} + +/** + * The base implementation of `getTag`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +function baseGetTag(value) { + return objectToString.call(value); +} + +/** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ +function baseHasIn(object, key) { + return object != null && key in Object(object); +} + +/** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @param {boolean} [bitmask] The bitmask of comparison flags. + * The bitmask may be composed of the following flags: + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ +function baseIsEqual(value, other, customizer, bitmask, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack); +} + +/** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} [customizer] The function to customize comparisons. + * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = arrayTag, + othTag = arrayTag; + + if (!objIsArr) { + objTag = getTag(object); + objTag = objTag == argsTag ? objectTag : objTag; + } + if (!othIsArr) { + othTag = getTag(other); + othTag = othTag == argsTag ? objectTag : othTag; + } + var objIsObj = objTag == objectTag && !isHostObject(object), + othIsObj = othTag == objectTag && !isHostObject(other), + isSameTag = objTag == othTag; + + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) + : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack); + } + if (!(bitmask & PARTIAL_COMPARE_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, equalFunc, customizer, bitmask, stack); +} + +/** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ +function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack) + : result + )) { + return false; + } + } + } + return true; +} + +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ +function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); +} + +/** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ +function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[objectToString.call(value)]; +} + +/** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ +function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); +} + +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; +} + +/** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; +} + +/** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ +function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; +} + +/** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ +function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG); + }; +} + +/** + * The base implementation of `_.orderBy` without param guards. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {string[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. + */ +function baseOrderBy(collection, iteratees, orders) { + var index = -1; + iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(baseIteratee)); + + var result = baseMap(collection, function(value, key, collection) { + var criteria = arrayMap(iteratees, function(iteratee) { + return iteratee(value); + }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); + + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); +} + +/** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ +function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; +} + +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest(func, start) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = array; + return apply(func, this, otherArgs); + }; +} + +/** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ +function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +} + +/** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast property path array. + */ +function castPath(value) { + return isArray(value) ? value : stringToPath(value); +} + +/** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ +function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = isSymbol(value); + + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = isSymbol(other); + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; +} + +/** + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. + * + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]|string[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. + */ +function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; + + while (++index < length) { + var result = compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * (order == 'desc' ? -1 : 1); + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; +} + +/** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ +function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; +} + +/** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ +function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; +} + +/** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} customizer The function to customize comparisons. + * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ +function equalArrays(array, other, equalFunc, customizer, bitmask, stack) { + var isPartial = bitmask & PARTIAL_COMPARE_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, + result = true, + seen = (bitmask & UNORDERED_COMPARE_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!seen.has(othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) { + return seen.add(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, customizer, bitmask, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; +} + +/** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} customizer The function to customize comparisons. + * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & PARTIAL_COMPARE_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= UNORDERED_COMPARE_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; +} + +/** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} customizer The function to customize comparisons. + * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` + * for more details. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalObjects(object, other, equalFunc, customizer, bitmask, stack) { + var isPartial = bitmask & PARTIAL_COMPARE_FLAG, + objProps = keys(object), + objLength = objProps.length, + othProps = keys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; +} + +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ +function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; +} + +/** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ +function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; +} + +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; +} + +/** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +var getTag = baseGetTag; + +// Fallback for data views, maps, sets, and weak maps in IE 11, +// for data views in Edge < 14, and promises in Node.js. +if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = objectToString.call(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : undefined; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; +} + +/** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ +function hasPath(object, path, hasFunc) { + path = isKey(path, object) ? [path] : castPath(path); + + var result, + index = -1, + length = path.length; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result) { + return result; + } + var length = object ? object.length : 0; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); +} + +/** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ +function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); +} + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); +} + +/** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ +function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; +} + +/** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ +function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); +} + +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); +} + +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); +} + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; +} + +/** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ +function isStrictComparable(value) { + return value === value && !isObject(value); +} + +/** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ +function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; +} + +/** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ +var stringToPath = memoize(function(string) { + string = toString(string); + + var result = []; + if (reLeadingDot.test(string)) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, string) { + result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; +}); + +/** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ +function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +} + +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to process. + * @returns {string} Returns the source code. + */ +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; +} + +/** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, function(o) { return o.user; }); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] + * + * _.sortBy(users, 'user', function(o) { + * return Math.floor(o.age / 10); + * }); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + */ +var sortBy = baseRest(function(collection, iteratees) { + if (collection == null) { + return []; + } + var length = iteratees.length; + if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { + iteratees = []; + } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { + iteratees = [iteratees[0]]; + } + return baseOrderBy(collection, baseFlatten(iteratees, 1), []); +}); + +/** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ +function memoize(func, resolver) { + if (typeof func != 'function' || (resolver && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result); + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; +} + +// Assign cache to `_.memoize`. +memoize.Cache = MapCache; + +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} + +/** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ +var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + +/** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {string} Returns the string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ +function toString(value) { + return value == null ? '' : baseToString(value); +} + +/** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ +function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; +} + +/** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ +function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); +} + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} + +/** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ +function identity(value) { + return value; +} + +/** + * Creates a function that returns the value at `path` of a given object. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + * @example + * + * var objects = [ + * { 'a': { 'b': 2 } }, + * { 'a': { 'b': 1 } } + * ]; + * + * _.map(objects, _.property('a.b')); + * // => [2, 1] + * + * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); + * // => [1, 2] + */ +function property(path) { + return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); +} + +module.exports = sortBy; +}); + +var implementation = class URLSearchParamsImpl { + constructor(constructorArgs, { doNotStripQMark = false }) { + let init = constructorArgs[0]; + this._list = []; + this._url = null; + + if (!doNotStripQMark && typeof init === "string" && init[0] === "?") { + init = init.slice(1); + } + + if (Array.isArray(init)) { + for (const pair of init) { + if (pair.length !== 2) { + throw new TypeError("Failed to construct 'URLSearchParams': parameter 1 sequence's element does not " + + "contain exactly two elements."); + } + this._list.push([pair[0], pair[1]]); + } + } else if (typeof init === "object" && Object.getPrototypeOf(init) === null) { + for (const name of Object.keys(init)) { + const value = init[name]; + this._list.push([name, value]); + } + } else { + this._list = urlencoded.parseUrlencoded(init); + } + } + + _updateSteps() { + if (this._url !== null) { + let query = urlencoded.serializeUrlencoded(this._list); + if (query === "") { + query = null; + } + this._url._url.query = query; + } + } + + append(name, value) { + this._list.push([name, value]); + this._updateSteps(); + } + + delete(name) { + let i = 0; + while (i < this._list.length) { + if (this._list[i][0] === name) { + this._list.splice(i, 1); + } else { + i++; + } + } + this._updateSteps(); + } + + get(name) { + for (const tuple of this._list) { + if (tuple[0] === name) { + return tuple[1]; + } + } + return null; + } + + getAll(name) { + const output = []; + for (const tuple of this._list) { + if (tuple[0] === name) { + output.push(tuple[1]); + } + } + return output; + } + + has(name) { + for (const tuple of this._list) { + if (tuple[0] === name) { + return true; + } + } + return false; + } + + set(name, value) { + let found = false; + let i = 0; + while (i < this._list.length) { + if (this._list[i][0] === name) { + if (found) { + this._list.splice(i, 1); + } else { + found = true; + this._list[i][1] = value; + i++; + } + } else { + i++; + } + } + if (!found) { + this._list.push([name, value]); + } + this._updateSteps(); + } + + sort() { + this._list = lodash_sortby(this._list, [0]); + this._updateSteps(); + } + + [Symbol.iterator]() { + return this._list[Symbol.iterator](); + } + + toString() { + return urlencoded.serializeUrlencoded(this._list); + } +}; + +var URLSearchParamsImpl_1 = { + implementation: implementation +}; + +var URLSearchParams_1 = createCommonjsModule(function (module) { + + + + +const impl = utils.implSymbol; + +const IteratorPrototype = Object.create(utils.IteratorPrototype, { + next: { + value: function next() { + const internal = this[utils.iterInternalSymbol]; + const { target, kind, index } = internal; + const values = Array.from(target[impl]); + const len = values.length; + if (index >= len) { + return { value: undefined, done: true }; + } + + const pair = values[index]; + internal.index = index + 1; + const [key, value] = pair.map(utils.tryWrapperForImpl); + + let result; + switch (kind) { + case "key": + result = key; + break; + case "value": + result = value; + break; + case "key+value": + result = [key, value]; + break; + } + return { value: result, done: false }; + }, + writable: true, + enumerable: true, + configurable: true + }, + [Symbol.toStringTag]: { + value: "URLSearchParamsIterator", + writable: false, + enumerable: false, + configurable: true + } +}); + +function URLSearchParams() { + const args = []; + for (let i = 0; i < arguments.length && i < 1; ++i) { + args[i] = arguments[i]; + } + + if (args[0] !== undefined) { + if (utils.isObject(args[0])) { + if (args[0][Symbol.iterator] !== undefined) { + if (!utils.isObject(args[0])) { + throw new TypeError( + "Failed to construct 'URLSearchParams': parameter 1" + " sequence" + " is not an iterable object." + ); + } else { + const V = []; + const tmp = args[0]; + for (let nextItem of tmp) { + if (!utils.isObject(nextItem)) { + throw new TypeError( + "Failed to construct 'URLSearchParams': parameter 1" + + " sequence" + + "'s element" + + " is not an iterable object." + ); + } else { + const V = []; + const tmp = nextItem; + for (let nextItem of tmp) { + nextItem = lib$2["USVString"](nextItem, { + context: + "Failed to construct 'URLSearchParams': parameter 1" + " sequence" + "'s element" + "'s element" + }); + + V.push(nextItem); + } + nextItem = V; + } + + V.push(nextItem); + } + args[0] = V; + } + } else { + if (!utils.isObject(args[0])) { + throw new TypeError("Failed to construct 'URLSearchParams': parameter 1" + " record" + " is not an object."); + } else { + const result = Object.create(null); + for (const key of Reflect.ownKeys(args[0])) { + const desc = Object.getOwnPropertyDescriptor(args[0], key); + if (desc && desc.enumerable) { + let typedKey = key; + let typedValue = args[0][key]; + + typedKey = lib$2["USVString"](typedKey, { + context: "Failed to construct 'URLSearchParams': parameter 1" + " record" + "'s key" + }); + + typedValue = lib$2["USVString"](typedValue, { + context: "Failed to construct 'URLSearchParams': parameter 1" + " record" + "'s value" + }); + + result[typedKey] = typedValue; + } + } + args[0] = result; + } + } + } else { + args[0] = lib$2["USVString"](args[0], { context: "Failed to construct 'URLSearchParams': parameter 1" }); + } + } else { + args[0] = ""; + } + + iface.setup(this, args); +} + +Object.defineProperty(URLSearchParams, "prototype", { + value: URLSearchParams.prototype, + writable: false, + enumerable: false, + configurable: false +}); + +Object.defineProperty(URLSearchParams.prototype, Symbol.iterator, { + writable: true, + enumerable: false, + configurable: true, + value: function entries() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + return module.exports.createDefaultIterator(this, "key+value"); + } +}); +URLSearchParams.prototype.forEach = function forEach(callback) { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + if (arguments.length < 1) { + throw new TypeError( + "Failed to execute 'forEach' on 'URLSearchParams': 1 argument required, " + "but only 0 present." + ); + } + if (typeof callback !== "function") { + throw new TypeError( + "Failed to execute 'forEach' on 'URLSearchParams': The callback provided " + "as parameter 1 is not a function." + ); + } + const thisArg = arguments[1]; + let pairs = Array.from(this[impl]); + let i = 0; + while (i < pairs.length) { + const [key, value] = pairs[i].map(utils.tryWrapperForImpl); + callback.call(thisArg, value, key, this); + pairs = Array.from(this[impl]); + i++; + } +}; +URLSearchParams.prototype.append = function append(name, value) { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + if (arguments.length < 2) { + throw new TypeError( + "Failed to execute 'append' on 'URLSearchParams': 2 " + + "arguments required, but only " + + arguments.length + + " present." + ); + } + + const args = []; + for (let i = 0; i < arguments.length && i < 2; ++i) { + args[i] = arguments[i]; + } + + args[0] = lib$2["USVString"](args[0], { + context: "Failed to execute 'append' on 'URLSearchParams': parameter 1" + }); + + args[1] = lib$2["USVString"](args[1], { + context: "Failed to execute 'append' on 'URLSearchParams': parameter 2" + }); + + return this[impl].append(...args); +}; + +URLSearchParams.prototype.delete = function _(name) { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + if (arguments.length < 1) { + throw new TypeError( + "Failed to execute 'delete' on 'URLSearchParams': 1 " + + "argument required, but only " + + arguments.length + + " present." + ); + } + + const args = []; + for (let i = 0; i < arguments.length && i < 1; ++i) { + args[i] = arguments[i]; + } + + args[0] = lib$2["USVString"](args[0], { + context: "Failed to execute 'delete' on 'URLSearchParams': parameter 1" + }); + + return this[impl].delete(...args); +}; + +URLSearchParams.prototype.get = function get(name) { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + if (arguments.length < 1) { + throw new TypeError( + "Failed to execute 'get' on 'URLSearchParams': 1 " + + "argument required, but only " + + arguments.length + + " present." + ); + } + + const args = []; + for (let i = 0; i < arguments.length && i < 1; ++i) { + args[i] = arguments[i]; + } + + args[0] = lib$2["USVString"](args[0], { context: "Failed to execute 'get' on 'URLSearchParams': parameter 1" }); + + return this[impl].get(...args); +}; + +URLSearchParams.prototype.getAll = function getAll(name) { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + if (arguments.length < 1) { + throw new TypeError( + "Failed to execute 'getAll' on 'URLSearchParams': 1 " + + "argument required, but only " + + arguments.length + + " present." + ); + } + + const args = []; + for (let i = 0; i < arguments.length && i < 1; ++i) { + args[i] = arguments[i]; + } + + args[0] = lib$2["USVString"](args[0], { + context: "Failed to execute 'getAll' on 'URLSearchParams': parameter 1" + }); + + return utils.tryWrapperForImpl(this[impl].getAll(...args)); +}; + +URLSearchParams.prototype.has = function has(name) { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + if (arguments.length < 1) { + throw new TypeError( + "Failed to execute 'has' on 'URLSearchParams': 1 " + + "argument required, but only " + + arguments.length + + " present." + ); + } + + const args = []; + for (let i = 0; i < arguments.length && i < 1; ++i) { + args[i] = arguments[i]; + } + + args[0] = lib$2["USVString"](args[0], { context: "Failed to execute 'has' on 'URLSearchParams': parameter 1" }); + + return this[impl].has(...args); +}; + +URLSearchParams.prototype.set = function set(name, value) { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + if (arguments.length < 2) { + throw new TypeError( + "Failed to execute 'set' on 'URLSearchParams': 2 " + + "arguments required, but only " + + arguments.length + + " present." + ); + } + + const args = []; + for (let i = 0; i < arguments.length && i < 2; ++i) { + args[i] = arguments[i]; + } + + args[0] = lib$2["USVString"](args[0], { context: "Failed to execute 'set' on 'URLSearchParams': parameter 1" }); + + args[1] = lib$2["USVString"](args[1], { context: "Failed to execute 'set' on 'URLSearchParams': parameter 2" }); + + return this[impl].set(...args); +}; + +URLSearchParams.prototype.sort = function sort() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + return this[impl].sort(); +}; + +URLSearchParams.prototype.toString = function toString() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + return this[impl].toString(); +}; + +URLSearchParams.prototype.entries = URLSearchParams.prototype[Symbol.iterator]; + +URLSearchParams.prototype.keys = function keys() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + return module.exports.createDefaultIterator(this, "key"); +}; + +URLSearchParams.prototype.values = function values() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + return module.exports.createDefaultIterator(this, "value"); +}; + +Object.defineProperty(URLSearchParams.prototype, Symbol.toStringTag, { + value: "URLSearchParams", + writable: false, + enumerable: false, + configurable: true +}); + +const iface = { + mixedInto: [], + is(obj) { + if (obj) { + if (obj[impl] instanceof URLSearchParamsImpl_1.implementation) { + return true; + } + for (let i = 0; i < module.exports.mixedInto.length; ++i) { + if (obj instanceof module.exports.mixedInto[i]) { + return true; + } + } + } + return false; + }, + isImpl(obj) { + if (obj) { + if (obj instanceof URLSearchParamsImpl_1.implementation) { + return true; + } + + const wrapper = utils.wrapperForImpl(obj); + for (let i = 0; i < module.exports.mixedInto.length; ++i) { + if (wrapper instanceof module.exports.mixedInto[i]) { + return true; + } + } + } + return false; + }, + convert(obj, { context = "The provided value" } = {}) { + if (module.exports.is(obj)) { + return utils.implForWrapper(obj); + } + throw new TypeError(`${context} is not of type 'URLSearchParams'.`); + }, + + createDefaultIterator(target, kind) { + const iterator = Object.create(IteratorPrototype); + Object.defineProperty(iterator, utils.iterInternalSymbol, { + value: { target, kind, index: 0 }, + writable: false, + enumerable: false, + configurable: true + }); + return iterator; + }, + + create(constructorArgs, privateData) { + let obj = Object.create(URLSearchParams.prototype); + obj = this.setup(obj, constructorArgs, privateData); + return obj; + }, + createImpl(constructorArgs, privateData) { + let obj = Object.create(URLSearchParams.prototype); + obj = this.setup(obj, constructorArgs, privateData); + return utils.implForWrapper(obj); + }, + _internalSetup(obj) {}, + setup(obj, constructorArgs, privateData) { + if (!privateData) privateData = {}; + + privateData.wrapper = obj; + + this._internalSetup(obj); + Object.defineProperty(obj, impl, { + value: new URLSearchParamsImpl_1.implementation(constructorArgs, privateData), + writable: false, + enumerable: false, + configurable: true + }); + + obj[impl][utils.wrapperSymbol] = obj; + if (URLSearchParamsImpl_1.init) { + URLSearchParamsImpl_1.init(obj[impl], privateData); + } + return obj; + }, + interface: URLSearchParams, + expose: { + Window: { URLSearchParams }, + Worker: { URLSearchParams } + } +}; // iface +module.exports = iface; +}); + +var implementation$1 = class URLImpl { + constructor(constructorArgs) { + const url = constructorArgs[0]; + const base = constructorArgs[1]; + + let parsedBase = null; + if (base !== undefined) { + parsedBase = urlStateMachine.basicURLParse(base); + if (parsedBase === null) { + throw new TypeError("Invalid base URL"); + } + } + + const parsedURL = urlStateMachine.basicURLParse(url, { baseURL: parsedBase }); + if (parsedURL === null) { + throw new TypeError("Invalid URL"); + } + + const query = parsedURL.query !== null ? parsedURL.query : ""; + + this._url = parsedURL; + + // We cannot invoke the "new URLSearchParams object" algorithm without going through the constructor, which strips + // question mark by default. Therefore the doNotStripQMark hack is used. + this._query = URLSearchParams_1.createImpl([query], { doNotStripQMark: true }); + this._query._url = this; + } + + get href() { + return urlStateMachine.serializeURL(this._url); + } + + set href(v) { + const parsedURL = urlStateMachine.basicURLParse(v); + if (parsedURL === null) { + throw new TypeError("Invalid URL"); + } + + this._url = parsedURL; + + this._query._list.splice(0); + const { query } = parsedURL; + if (query !== null) { + this._query._list = urlencoded.parseUrlencoded(query); + } + } + + get origin() { + return urlStateMachine.serializeURLOrigin(this._url); + } + + get protocol() { + return this._url.scheme + ":"; + } + + set protocol(v) { + urlStateMachine.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" }); + } + + get username() { + return this._url.username; + } + + set username(v) { + if (urlStateMachine.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + urlStateMachine.setTheUsername(this._url, v); + } + + get password() { + return this._url.password; + } + + set password(v) { + if (urlStateMachine.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + urlStateMachine.setThePassword(this._url, v); + } + + get host() { + const url = this._url; + + if (url.host === null) { + return ""; + } + + if (url.port === null) { + return urlStateMachine.serializeHost(url.host); + } + + return urlStateMachine.serializeHost(url.host) + ":" + urlStateMachine.serializeInteger(url.port); + } + + set host(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + urlStateMachine.basicURLParse(v, { url: this._url, stateOverride: "host" }); + } + + get hostname() { + if (this._url.host === null) { + return ""; + } + + return urlStateMachine.serializeHost(this._url.host); + } + + set hostname(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + urlStateMachine.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); + } + + get port() { + if (this._url.port === null) { + return ""; + } + + return urlStateMachine.serializeInteger(this._url.port); + } + + set port(v) { + if (urlStateMachine.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + if (v === "") { + this._url.port = null; + } else { + urlStateMachine.basicURLParse(v, { url: this._url, stateOverride: "port" }); + } + } + + get pathname() { + if (this._url.cannotBeABaseURL) { + return this._url.path[0]; + } + + if (this._url.path.length === 0) { + return ""; + } + + return "/" + this._url.path.join("/"); + } + + set pathname(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + this._url.path = []; + urlStateMachine.basicURLParse(v, { url: this._url, stateOverride: "path start" }); + } + + get search() { + if (this._url.query === null || this._url.query === "") { + return ""; + } + + return "?" + this._url.query; + } + + set search(v) { + const url = this._url; + + if (v === "") { + url.query = null; + this._query._list = []; + return; + } + + const input = v[0] === "?" ? v.substring(1) : v; + url.query = ""; + urlStateMachine.basicURLParse(input, { url, stateOverride: "query" }); + this._query._list = urlencoded.parseUrlencoded(input); + } + + get searchParams() { + return this._query; + } + + get hash() { + if (this._url.fragment === null || this._url.fragment === "") { + return ""; + } + + return "#" + this._url.fragment; + } + + set hash(v) { + if (v === "") { + this._url.fragment = null; + return; + } + + const input = v[0] === "#" ? v.substring(1) : v; + this._url.fragment = ""; + urlStateMachine.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); + } + + toJSON() { + return this.href; + } +}; + +var URLImpl_1 = { + implementation: implementation$1 +}; + +var URL_1 = createCommonjsModule(function (module) { + + + + +const impl = utils.implSymbol; + +function URL(url) { + if (!new.target) { + throw new TypeError( + "Failed to construct 'URL'. Please use the 'new' operator; this constructor " + "cannot be called as a function." + ); + } + if (arguments.length < 1) { + throw new TypeError( + "Failed to construct 'URL': 1 " + "argument required, but only " + arguments.length + " present." + ); + } + + const args = []; + for (let i = 0; i < arguments.length && i < 2; ++i) { + args[i] = arguments[i]; + } + + args[0] = lib$2["USVString"](args[0], { context: "Failed to construct 'URL': parameter 1" }); + + if (args[1] !== undefined) { + args[1] = lib$2["USVString"](args[1], { context: "Failed to construct 'URL': parameter 2" }); + } + + iface.setup(this, args); +} + +Object.defineProperty(URL, "prototype", { + value: URL.prototype, + writable: false, + enumerable: false, + configurable: false +}); + +URL.prototype.toJSON = function toJSON() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + return this[impl].toJSON(); +}; + +Object.defineProperty(URL.prototype, "href", { + get() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + return this[impl]["href"]; + }, + + set(V) { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + V = lib$2["USVString"](V, { context: "Failed to set the 'href' property on 'URL': The provided value" }); + + this[impl]["href"] = V; + }, + + enumerable: true, + configurable: true +}); + +URL.prototype.toString = function toString() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + return this[impl]["href"]; +}; + +Object.defineProperty(URL.prototype, "origin", { + get() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + return this[impl]["origin"]; + }, + + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "protocol", { + get() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + return this[impl]["protocol"]; + }, + + set(V) { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + V = lib$2["USVString"](V, { context: "Failed to set the 'protocol' property on 'URL': The provided value" }); + + this[impl]["protocol"] = V; + }, + + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "username", { + get() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + return this[impl]["username"]; + }, + + set(V) { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + V = lib$2["USVString"](V, { context: "Failed to set the 'username' property on 'URL': The provided value" }); + + this[impl]["username"] = V; + }, + + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "password", { + get() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + return this[impl]["password"]; + }, + + set(V) { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + V = lib$2["USVString"](V, { context: "Failed to set the 'password' property on 'URL': The provided value" }); + + this[impl]["password"] = V; + }, + + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "host", { + get() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + return this[impl]["host"]; + }, + + set(V) { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + V = lib$2["USVString"](V, { context: "Failed to set the 'host' property on 'URL': The provided value" }); + + this[impl]["host"] = V; + }, + + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "hostname", { + get() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + return this[impl]["hostname"]; + }, + + set(V) { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + V = lib$2["USVString"](V, { context: "Failed to set the 'hostname' property on 'URL': The provided value" }); + + this[impl]["hostname"] = V; + }, + + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "port", { + get() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + return this[impl]["port"]; + }, + + set(V) { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + V = lib$2["USVString"](V, { context: "Failed to set the 'port' property on 'URL': The provided value" }); + + this[impl]["port"] = V; + }, + + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "pathname", { + get() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + return this[impl]["pathname"]; + }, + + set(V) { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + V = lib$2["USVString"](V, { context: "Failed to set the 'pathname' property on 'URL': The provided value" }); + + this[impl]["pathname"] = V; + }, + + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "search", { + get() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + return this[impl]["search"]; + }, + + set(V) { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + V = lib$2["USVString"](V, { context: "Failed to set the 'search' property on 'URL': The provided value" }); + + this[impl]["search"] = V; + }, + + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "searchParams", { + get() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + return utils.getSameObject(this, "searchParams", () => { + return utils.tryWrapperForImpl(this[impl]["searchParams"]); + }); + }, + + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "hash", { + get() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + return this[impl]["hash"]; + }, + + set(V) { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + + V = lib$2["USVString"](V, { context: "Failed to set the 'hash' property on 'URL': The provided value" }); + + this[impl]["hash"] = V; + }, + + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, Symbol.toStringTag, { + value: "URL", + writable: false, + enumerable: false, + configurable: true +}); + +const iface = { + mixedInto: [], + is(obj) { + if (obj) { + if (obj[impl] instanceof URLImpl_1.implementation) { + return true; + } + for (let i = 0; i < module.exports.mixedInto.length; ++i) { + if (obj instanceof module.exports.mixedInto[i]) { + return true; + } + } + } + return false; + }, + isImpl(obj) { + if (obj) { + if (obj instanceof URLImpl_1.implementation) { + return true; + } + + const wrapper = utils.wrapperForImpl(obj); + for (let i = 0; i < module.exports.mixedInto.length; ++i) { + if (wrapper instanceof module.exports.mixedInto[i]) { + return true; + } + } + } + return false; + }, + convert(obj, { context = "The provided value" } = {}) { + if (module.exports.is(obj)) { + return utils.implForWrapper(obj); + } + throw new TypeError(`${context} is not of type 'URL'.`); + }, + + create(constructorArgs, privateData) { + let obj = Object.create(URL.prototype); + obj = this.setup(obj, constructorArgs, privateData); + return obj; + }, + createImpl(constructorArgs, privateData) { + let obj = Object.create(URL.prototype); + obj = this.setup(obj, constructorArgs, privateData); + return utils.implForWrapper(obj); + }, + _internalSetup(obj) {}, + setup(obj, constructorArgs, privateData) { + if (!privateData) privateData = {}; + + privateData.wrapper = obj; + + this._internalSetup(obj); + Object.defineProperty(obj, impl, { + value: new URLImpl_1.implementation(constructorArgs, privateData), + writable: false, + enumerable: false, + configurable: true + }); + + obj[impl][utils.wrapperSymbol] = obj; + if (URLImpl_1.init) { + URLImpl_1.init(obj[impl], privateData); + } + return obj; + }, + interface: URL, + expose: { + Window: { URL }, + Worker: { URL } + } +}; // iface +module.exports = iface; +}); + +var URL$1 = URL_1.interface; +var URLSearchParams = URLSearchParams_1.interface; + +var parseURL = urlStateMachine.parseURL; +var basicURLParse = urlStateMachine.basicURLParse; +var serializeURL = urlStateMachine.serializeURL; +var serializeHost = urlStateMachine.serializeHost; +var serializeInteger = urlStateMachine.serializeInteger; +var serializeURLOrigin = urlStateMachine.serializeURLOrigin; +var setTheUsername = urlStateMachine.setTheUsername; +var setThePassword = urlStateMachine.setThePassword; +var cannotHaveAUsernamePasswordPort = urlStateMachine.cannotHaveAUsernamePasswordPort; + +var percentDecode$1 = urlencoded.percentDecode; + +var publicApi = { + URL: URL$1, + URLSearchParams: URLSearchParams, + parseURL: parseURL, + basicURLParse: basicURLParse, + serializeURL: serializeURL, + serializeHost: serializeHost, + serializeInteger: serializeInteger, + serializeURLOrigin: serializeURLOrigin, + setTheUsername: setTheUsername, + setThePassword: setThePassword, + cannotHaveAUsernamePasswordPort: cannotHaveAUsernamePasswordPort, + percentDecode: percentDecode$1 +}; + +var require$$0 = getCjsExportFromNamespace(lib); + +// avoid circular dependency when using jest.mock() +let fetch$1; +try { + // note that jest is not a global, but is injected somehow into + // the environment. So we can't be safe and check for global.jest + // Hence the try/catch + fetch$1 = jest.requireActual('node-fetch'); //eslint-disable-line no-undef +} catch (e) { + fetch$1 = require$$0; +} +const Request$1 = fetch$1.Request; +const Response$1 = fetch$1.Response; +const Headers$1 = fetch$1.Headers; + + + +const { setUrlImplementation } = requestUtils; +setUrlImplementation(publicApi.URL); + +lib$1.global = commonjsGlobal; +lib$1.statusTextMap = http.STATUS_CODES; +lib$1.Stream = Stream; + +lib$1.config = Object.assign(lib$1.config, { + Promise, + Request: Request$1, + Response: Response$1, + Headers: Headers$1, + fetch: fetch$1, +}); + +var server = lib$1.createInstance(); + +export default server;