diff --git a/node_modules/eslint-plugin-react-hooks/LICENSE b/node_modules/eslint-plugin-react-hooks/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b93be90515ccd0b9daedaa589e42bf5929693f1f --- /dev/null +++ b/node_modules/eslint-plugin-react-hooks/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/eslint-plugin-react-hooks/README.md b/node_modules/eslint-plugin-react-hooks/README.md new file mode 100644 index 0000000000000000000000000000000000000000..36f63722f7268fc7be8d6c9f8ccbb57d9e613bd8 --- /dev/null +++ b/node_modules/eslint-plugin-react-hooks/README.md @@ -0,0 +1,109 @@ +# `eslint-plugin-react-hooks` + +This ESLint plugin enforces the [Rules of Hooks](https://react.dev/reference/rules/rules-of-hooks). + +It is a part of the [Hooks API](https://react.dev/reference/react/hooks) for React. + +## Installation + +**Note: If you're using Create React App, please use `react-scripts` >= 3 instead of adding it directly.** + +Assuming you already have ESLint installed, run: + +```sh +# npm +npm install eslint-plugin-react-hooks --save-dev + +# yarn +yarn add eslint-plugin-react-hooks --dev +``` + +### Legacy Config (.eslintrc) + +If you are still using ESLint below 9.0.0, please continue to use `recommended-legacy`. To avoid breaking changes, we still support `recommended` as well, but note that this will be changed to alias the flat recommended config in v6. + +```js +{ + "extends": [ + // ... + "plugin:react-hooks/recommended-legacy" + ] +} +``` + +### Flat Config (eslint.config.js) + +For [ESLint 9.0.0 and above](https://eslint.org/blog/2024/04/eslint-v9.0.0-released/) users, add the `recommended-latest` config. + +```js +import reactHooks from 'eslint-plugin-react-hooks'; + +export default [ + // ... + reactHooks.configs['recommended-latest'], +]; +``` + +### Custom Configuration + +If you want more fine-grained configuration, you can instead add a snippet like this to your ESLint configuration file: + +#### Legacy Config (.eslintrc) + +```js +{ + "plugins": [ + // ... + "react-hooks" + ], + "rules": { + // ... + "react-hooks/rules-of-hooks": "error", + "react-hooks/exhaustive-deps": "warn" + } +} +``` + +#### Flat Config (eslint.config.js) + +```js +import reactHooks from 'eslint-plugin-react-hooks'; + +export default [ + { + files: ['**/*.{js,jsx}'], + plugins: { 'react-hooks': reactHooks }, + // ... + rules: { + 'react-hooks/rules-of-hooks': 'error', + 'react-hooks/exhaustive-deps': 'warn', + } + }, +]; +``` + +## Advanced Configuration + +`exhaustive-deps` can be configured to validate dependencies of custom Hooks with the `additionalHooks` option. +This option accepts a regex to match the names of custom Hooks that have dependencies. + +```js +{ + "rules": { + // ... + "react-hooks/exhaustive-deps": ["warn", { + "additionalHooks": "(useMyCustomHook|useMyOtherCustomHook)" + }] + } +} +``` + +We suggest to use this option **very sparingly, if at all**. Generally saying, we recommend most custom Hooks to not use the dependencies argument, and instead provide a higher-level API that is more focused around a specific use case. + +## Valid and Invalid Examples + +Please refer to the [Rules of Hooks](https://react.dev/reference/rules/rules-of-hooks) documentation to learn more about this rule. + +## License + +MIT diff --git a/node_modules/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.d.ts b/node_modules/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d68634901168333725752c8943b97fe8d06e7af3 --- /dev/null +++ b/node_modules/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.d.ts @@ -0,0 +1,91 @@ +import * as estree from 'estree'; +import { Rule, ESLint } from 'eslint'; + +declare const rules: { + 'rules-of-hooks': { + meta: { + type: "problem"; + docs: { + description: string; + recommended: true; + url: string; + }; + }; + create(context: Rule.RuleContext): { + onCodePathSegmentStart: (segment: Rule.CodePathSegment) => number; + onCodePathSegmentEnd: () => Rule.CodePathSegment | undefined; + onCodePathStart: () => number; + onCodePathEnd(codePath: Rule.CodePath, codePathNode: Rule.Node): void; + CallExpression(node: estree.CallExpression & Rule.NodeParentExtension): void; + Identifier(node: estree.Identifier & Rule.NodeParentExtension): void; + 'CallExpression:exit'(node: estree.CallExpression & Rule.NodeParentExtension): void; + FunctionDeclaration(node: estree.FunctionDeclaration & Rule.NodeParentExtension): void; + ArrowFunctionExpression(node: estree.ArrowFunctionExpression & Rule.NodeParentExtension): void; + }; + }; + 'exhaustive-deps': { + meta: { + type: "suggestion"; + docs: { + description: string; + recommended: true; + url: string; + }; + fixable: "code"; + hasSuggestions: true; + schema: { + type: "object"; + additionalProperties: false; + enableDangerousAutofixThisMayCauseInfiniteLoops: boolean; + properties: { + additionalHooks: { + type: "string"; + }; + enableDangerousAutofixThisMayCauseInfiniteLoops: { + type: "boolean"; + }; + }; + }[]; + }; + create(context: Rule.RuleContext): { + CallExpression: (node: estree.CallExpression) => void; + }; + }; +}; +declare const configs: { + /** Legacy recommended config, to be used with rc-based configurations */ + 'recommended-legacy': { + plugins: string[]; + rules: { + 'react-hooks/rules-of-hooks': "error"; + 'react-hooks/exhaustive-deps': "warn"; + }; + }; + /** + * 'recommended' is currently aliased to the legacy / rc recommended config) to maintain backwards compatibility. + * This is deprecated and in v6, it will switch to alias the flat recommended config. + */ + recommended: { + plugins: string[]; + rules: { + 'react-hooks/rules-of-hooks': "error"; + 'react-hooks/exhaustive-deps': "warn"; + }; + }; + /** Latest recommended config, to be used with flat configurations */ + 'recommended-latest': { + name: string; + plugins: { + readonly 'react-hooks': ESLint.Plugin; + }; + rules: { + 'react-hooks/rules-of-hooks': "error"; + 'react-hooks/exhaustive-deps': "warn"; + }; + }; +}; +declare const meta: { + name: string; +}; + +export { configs, meta, rules }; diff --git a/node_modules/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.development.js b/node_modules/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.development.js new file mode 100644 index 0000000000000000000000000000000000000000..128ec146542487b7f6b3d4785f0e812791e4891d --- /dev/null +++ b/node_modules/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.development.js @@ -0,0 +1,2737 @@ +/** + * @license React + * eslint-plugin-react-hooks.development.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +'use strict'; + +if (process.env.NODE_ENV !== "production") { + (function() { +'use strict'; + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise */ + + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +} + +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || from); +} + +/* eslint-disable no-for-of-loops/no-for-of-loops */ +/** + * Catch all identifiers that begin with "use" followed by an uppercase Latin + * character to exclude identifiers like "user". + */ +function isHookName(s) { + return s === 'use' || /^use[A-Z0-9]/.test(s); +} +/** + * We consider hooks to be a hook name identifier or a member expression + * containing a hook name. + */ +function isHook(node) { + if (node.type === 'Identifier') { + return isHookName(node.name); + } + else if (node.type === 'MemberExpression' && + !node.computed && + isHook(node.property)) { + var obj = node.object; + var isPascalCaseNameSpace = /^[A-Z].*/; + return obj.type === 'Identifier' && isPascalCaseNameSpace.test(obj.name); + } + else { + return false; + } +} +/** + * Checks if the node is a React component name. React component names must + * always start with an uppercase letter. + */ +function isComponentName(node) { + return node.type === 'Identifier' && /^[A-Z]/.test(node.name); +} +function isReactFunction(node, functionName) { + return (('name' in node && node.name === functionName) || + (node.type === 'MemberExpression' && + 'name' in node.object && + node.object.name === 'React' && + 'name' in node.property && + node.property.name === functionName)); +} +/** + * Checks if the node is a callback argument of forwardRef. This render function + * should follow the rules of hooks. + */ +function isForwardRefCallback(node) { + return !!(node.parent && + 'callee' in node.parent && + node.parent.callee && + isReactFunction(node.parent.callee, 'forwardRef')); +} +/** + * Checks if the node is a callback argument of React.memo. This anonymous + * functional component should follow the rules of hooks. + */ +function isMemoCallback(node) { + return !!(node.parent && + 'callee' in node.parent && + node.parent.callee && + isReactFunction(node.parent.callee, 'memo')); +} +function isInsideComponentOrHook(node) { + while (node) { + var functionName = getFunctionName(node); + if (functionName) { + if (isComponentName(functionName) || isHook(functionName)) { + return true; + } + } + if (isForwardRefCallback(node) || isMemoCallback(node)) { + return true; + } + node = node.parent; + } + return false; +} +function isInsideDoWhileLoop(node) { + while (node) { + if (node.type === 'DoWhileStatement') { + return true; + } + node = node.parent; + } + return false; +} +function isUseEffectEventIdentifier$1(node) { + return false; +} +function isUseIdentifier(node) { + return isReactFunction(node, 'use'); +} +var rule$1 = { + meta: { + type: 'problem', + docs: { + description: 'enforces the Rules of Hooks', + recommended: true, + url: 'https://reactjs.org/docs/hooks-rules.html', + }, + }, + create: function (context) { + var lastEffect = null; + var codePathReactHooksMapStack = []; + var codePathSegmentStack = []; + var useEffectEventFunctions = new WeakSet(); + // For a given scope, iterate through the references and add all useEffectEvent definitions. We can + // do this in non-Program nodes because we can rely on the assumption that useEffectEvent functions + // can only be declared within a component or hook at its top level. + function recordAllUseEffectEventFunctions(scope) { + var e_1, _a, e_2, _b; + try { + for (var _c = __values(scope.references), _d = _c.next(); !_d.done; _d = _c.next()) { + var reference = _d.value; + var parent = reference.identifier.parent; + if ((parent === null || parent === void 0 ? void 0 : parent.type) === 'VariableDeclarator' && + parent.init && + parent.init.type === 'CallExpression' && + parent.init.callee && + isUseEffectEventIdentifier$1(parent.init.callee)) { + if (reference.resolved === null) { + throw new Error('Unexpected null reference.resolved'); + } + try { + for (var _e = (e_2 = void 0, __values(reference.resolved.references)), _f = _e.next(); !_f.done; _f = _e.next()) { + var ref = _f.value; + if (ref !== reference) { + useEffectEventFunctions.add(ref.identifier); + } + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_f && !_f.done && (_b = _e.return)) _b.call(_e); + } + finally { if (e_2) throw e_2.error; } + } + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_d && !_d.done && (_a = _c.return)) _a.call(_c); + } + finally { if (e_1) throw e_1.error; } + } + } + /** + * SourceCode that also works down to ESLint 3.0.0 + */ + var getSourceCode = typeof context.getSourceCode === 'function' + ? function () { + return context.getSourceCode(); + } + : function () { + return context.sourceCode; + }; + /** + * SourceCode#getScope that also works down to ESLint 3.0.0 + */ + var getScope = typeof context.getScope === 'function' + ? function () { + return context.getScope(); + } + : function (node) { + return getSourceCode().getScope(node); + }; + return { + // Maintain code segment path stack as we traverse. + onCodePathSegmentStart: function (segment) { return codePathSegmentStack.push(segment); }, + onCodePathSegmentEnd: function () { return codePathSegmentStack.pop(); }, + // Maintain code path stack as we traverse. + onCodePathStart: function () { + return codePathReactHooksMapStack.push(new Map()); + }, + // Process our code path. + // + // Everything is ok if all React Hooks are both reachable from the initial + // segment and reachable from every final segment. + onCodePathEnd: function (codePath, codePathNode) { + var e_3, _a, e_4, _b, e_5, _c; + var reactHooksMap = codePathReactHooksMapStack.pop(); + if ((reactHooksMap === null || reactHooksMap === void 0 ? void 0 : reactHooksMap.size) === 0) { + return; + } + else if (typeof reactHooksMap === 'undefined') { + throw new Error('Unexpected undefined reactHooksMap'); + } + // All of the segments which are cyclic are recorded in this set. + var cyclic = new Set(); + /** + * Count the number of code paths from the start of the function to this + * segment. For example: + * + * ```js + * function MyComponent() { + * if (condition) { + * // Segment 1 + * } else { + * // Segment 2 + * } + * // Segment 3 + * } + * ``` + * + * Segments 1 and 2 have one path to the beginning of `MyComponent` and + * segment 3 has two paths to the beginning of `MyComponent` since we + * could have either taken the path of segment 1 or segment 2. + * + * Populates `cyclic` with cyclic segments. + */ + function countPathsFromStart(segment, pathHistory) { + var e_6, _a, e_7, _b; + var cache = countPathsFromStart.cache; + var paths = cache.get(segment.id); + var pathList = new Set(pathHistory); + // If `pathList` includes the current segment then we've found a cycle! + // We need to fill `cyclic` with all segments inside cycle + if (pathList.has(segment.id)) { + var pathArray = __spreadArray([], __read(pathList), false); + var cyclicSegments = pathArray.slice(pathArray.indexOf(segment.id) + 1); + try { + for (var cyclicSegments_1 = __values(cyclicSegments), cyclicSegments_1_1 = cyclicSegments_1.next(); !cyclicSegments_1_1.done; cyclicSegments_1_1 = cyclicSegments_1.next()) { + var cyclicSegment = cyclicSegments_1_1.value; + cyclic.add(cyclicSegment); + } + } + catch (e_6_1) { e_6 = { error: e_6_1 }; } + finally { + try { + if (cyclicSegments_1_1 && !cyclicSegments_1_1.done && (_a = cyclicSegments_1.return)) _a.call(cyclicSegments_1); + } + finally { if (e_6) throw e_6.error; } + } + return BigInt('0'); + } + // add the current segment to pathList + pathList.add(segment.id); + // We have a cached `paths`. Return it. + if (paths !== undefined) { + return paths; + } + if (codePath.thrownSegments.includes(segment)) { + paths = BigInt('0'); + } + else if (segment.prevSegments.length === 0) { + paths = BigInt('1'); + } + else { + paths = BigInt('0'); + try { + for (var _c = __values(segment.prevSegments), _d = _c.next(); !_d.done; _d = _c.next()) { + var prevSegment = _d.value; + paths += countPathsFromStart(prevSegment, pathList); + } + } + catch (e_7_1) { e_7 = { error: e_7_1 }; } + finally { + try { + if (_d && !_d.done && (_b = _c.return)) _b.call(_c); + } + finally { if (e_7) throw e_7.error; } + } + } + // If our segment is reachable then there should be at least one path + // to it from the start of our code path. + if (segment.reachable && paths === BigInt('0')) { + cache.delete(segment.id); + } + else { + cache.set(segment.id, paths); + } + return paths; + } + /** + * Count the number of code paths from this segment to the end of the + * function. For example: + * + * ```js + * function MyComponent() { + * // Segment 1 + * if (condition) { + * // Segment 2 + * } else { + * // Segment 3 + * } + * } + * ``` + * + * Segments 2 and 3 have one path to the end of `MyComponent` and + * segment 1 has two paths to the end of `MyComponent` since we could + * either take the path of segment 1 or segment 2. + * + * Populates `cyclic` with cyclic segments. + */ + function countPathsToEnd(segment, pathHistory) { + var e_8, _a, e_9, _b; + var cache = countPathsToEnd.cache; + var paths = cache.get(segment.id); + var pathList = new Set(pathHistory); + // If `pathList` includes the current segment then we've found a cycle! + // We need to fill `cyclic` with all segments inside cycle + if (pathList.has(segment.id)) { + var pathArray = Array.from(pathList); + var cyclicSegments = pathArray.slice(pathArray.indexOf(segment.id) + 1); + try { + for (var cyclicSegments_2 = __values(cyclicSegments), cyclicSegments_2_1 = cyclicSegments_2.next(); !cyclicSegments_2_1.done; cyclicSegments_2_1 = cyclicSegments_2.next()) { + var cyclicSegment = cyclicSegments_2_1.value; + cyclic.add(cyclicSegment); + } + } + catch (e_8_1) { e_8 = { error: e_8_1 }; } + finally { + try { + if (cyclicSegments_2_1 && !cyclicSegments_2_1.done && (_a = cyclicSegments_2.return)) _a.call(cyclicSegments_2); + } + finally { if (e_8) throw e_8.error; } + } + return BigInt('0'); + } + // add the current segment to pathList + pathList.add(segment.id); + // We have a cached `paths`. Return it. + if (paths !== undefined) { + return paths; + } + if (codePath.thrownSegments.includes(segment)) { + paths = BigInt('0'); + } + else if (segment.nextSegments.length === 0) { + paths = BigInt('1'); + } + else { + paths = BigInt('0'); + try { + for (var _c = __values(segment.nextSegments), _d = _c.next(); !_d.done; _d = _c.next()) { + var nextSegment = _d.value; + paths += countPathsToEnd(nextSegment, pathList); + } + } + catch (e_9_1) { e_9 = { error: e_9_1 }; } + finally { + try { + if (_d && !_d.done && (_b = _c.return)) _b.call(_c); + } + finally { if (e_9) throw e_9.error; } + } + } + cache.set(segment.id, paths); + return paths; + } + /** + * Gets the shortest path length to the start of a code path. + * For example: + * + * ```js + * function MyComponent() { + * if (condition) { + * // Segment 1 + * } + * // Segment 2 + * } + * ``` + * + * There is only one path from segment 1 to the code path start. Its + * length is one so that is the shortest path. + * + * There are two paths from segment 2 to the code path start. One + * through segment 1 with a length of two and another directly to the + * start with a length of one. The shortest path has a length of one + * so we would return that. + */ + function shortestPathLengthToStart(segment) { + var e_10, _a; + var cache = shortestPathLengthToStart.cache; + var length = cache.get(segment.id); + // If `length` is null then we found a cycle! Return infinity since + // the shortest path is definitely not the one where we looped. + if (length === null) { + return Infinity; + } + // We have a cached `length`. Return it. + if (length !== undefined) { + return length; + } + // Compute `length` and cache it. Guarding against cycles. + cache.set(segment.id, null); + if (segment.prevSegments.length === 0) { + length = 1; + } + else { + length = Infinity; + try { + for (var _b = __values(segment.prevSegments), _c = _b.next(); !_c.done; _c = _b.next()) { + var prevSegment = _c.value; + var prevLength = shortestPathLengthToStart(prevSegment); + if (prevLength < length) { + length = prevLength; + } + } + } + catch (e_10_1) { e_10 = { error: e_10_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + } + finally { if (e_10) throw e_10.error; } + } + length += 1; + } + cache.set(segment.id, length); + return length; + } + countPathsFromStart.cache = new Map(); + countPathsToEnd.cache = new Map(); + shortestPathLengthToStart.cache = new Map(); + // Count all code paths to the end of our component/hook. Also primes + // the `countPathsToEnd` cache. + var allPathsFromStartToEnd = countPathsToEnd(codePath.initialSegment); + // Gets the function name for our code path. If the function name is + // `undefined` then we know either that we have an anonymous function + // expression or our code path is not in a function. In both cases we + // will want to error since neither are React function components or + // hook functions - unless it is an anonymous function argument to + // forwardRef or memo. + var codePathFunctionName = getFunctionName(codePathNode); + // This is a valid code path for React hooks if we are directly in a React + // function component or we are in a hook function. + var isSomewhereInsideComponentOrHook = isInsideComponentOrHook(codePathNode); + var isDirectlyInsideComponentOrHook = codePathFunctionName + ? isComponentName(codePathFunctionName) || + isHook(codePathFunctionName) + : isForwardRefCallback(codePathNode) || isMemoCallback(codePathNode); + // Compute the earliest finalizer level using information from the + // cache. We expect all reachable final segments to have a cache entry + // after calling `visitSegment()`. + var shortestFinalPathLength = Infinity; + try { + for (var _d = __values(codePath.finalSegments), _e = _d.next(); !_e.done; _e = _d.next()) { + var finalSegment = _e.value; + if (!finalSegment.reachable) { + continue; + } + var length = shortestPathLengthToStart(finalSegment); + if (length < shortestFinalPathLength) { + shortestFinalPathLength = length; + } + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (_e && !_e.done && (_a = _d.return)) _a.call(_d); + } + finally { if (e_3) throw e_3.error; } + } + try { + // Make sure all React Hooks pass our lint invariants. Log warnings + // if not. + for (var reactHooksMap_1 = __values(reactHooksMap), reactHooksMap_1_1 = reactHooksMap_1.next(); !reactHooksMap_1_1.done; reactHooksMap_1_1 = reactHooksMap_1.next()) { + var _f = __read(reactHooksMap_1_1.value, 2), segment = _f[0], reactHooks = _f[1]; + // NOTE: We could report here that the hook is not reachable, but + // that would be redundant with more general "no unreachable" + // lint rules. + if (!segment.reachable) { + continue; + } + // If there are any final segments with a shorter path to start then + // we possibly have an early return. + // + // If our segment is a final segment itself then siblings could + // possibly be early returns. + var possiblyHasEarlyReturn = segment.nextSegments.length === 0 + ? shortestFinalPathLength <= shortestPathLengthToStart(segment) + : shortestFinalPathLength < shortestPathLengthToStart(segment); + // Count all the paths from the start of our code path to the end of + // our code path that go _through_ this segment. The critical piece + // of this is _through_. If we just call `countPathsToEnd(segment)` + // then we neglect that we may have gone through multiple paths to get + // to this point! Consider: + // + // ```js + // function MyComponent() { + // if (a) { + // // Segment 1 + // } else { + // // Segment 2 + // } + // // Segment 3 + // if (b) { + // // Segment 4 + // } else { + // // Segment 5 + // } + // } + // ``` + // + // In this component we have four code paths: + // + // 1. `a = true; b = true` + // 2. `a = true; b = false` + // 3. `a = false; b = true` + // 4. `a = false; b = false` + // + // From segment 3 there are two code paths to the end through segment + // 4 and segment 5. However, we took two paths to get here through + // segment 1 and segment 2. + // + // If we multiply the paths from start (two) by the paths to end (two) + // for segment 3 we get four. Which is our desired count. + var pathsFromStartToEnd = countPathsFromStart(segment) * countPathsToEnd(segment); + // Is this hook a part of a cyclic segment? + var cycled = cyclic.has(segment.id); + try { + for (var reactHooks_1 = (e_5 = void 0, __values(reactHooks)), reactHooks_1_1 = reactHooks_1.next(); !reactHooks_1_1.done; reactHooks_1_1 = reactHooks_1.next()) { + var hook = reactHooks_1_1.value; + // Report an error if a hook may be called more then once. + // `use(...)` can be called in loops. + if ((cycled || isInsideDoWhileLoop(hook)) && + !isUseIdentifier(hook)) { + context.report({ + node: hook, + message: "React Hook \"".concat(getSourceCode().getText(hook), "\" may be executed ") + + 'more than once. Possibly because it is called in a loop. ' + + 'React Hooks must be called in the exact same order in ' + + 'every component render.', + }); + } + // If this is not a valid code path for React hooks then we need to + // log a warning for every hook in this code path. + // + // Pick a special message depending on the scope this hook was + // called in. + if (isDirectlyInsideComponentOrHook) { + // Report an error if the hook is called inside an async function. + // @ts-expect-error the above check hasn't properly type-narrowed `codePathNode` (async doesn't exist on Node) + var isAsyncFunction = codePathNode.async; + if (isAsyncFunction) { + context.report({ + node: hook, + message: "React Hook \"".concat(getSourceCode().getText(hook), "\" cannot be ") + + 'called in an async function.', + }); + } + // Report an error if a hook does not reach all finalizing code + // path segments. + // + // Special case when we think there might be an early return. + if (!cycled && + pathsFromStartToEnd !== allPathsFromStartToEnd && + !isUseIdentifier(hook) && // `use(...)` can be called conditionally. + !isInsideDoWhileLoop(hook) // wrapping do/while loops are checked separately. + ) { + var message = "React Hook \"".concat(getSourceCode().getText(hook), "\" is called ") + + 'conditionally. React Hooks must be called in the exact ' + + 'same order in every component render.' + + (possiblyHasEarlyReturn + ? ' Did you accidentally call a React Hook after an' + + ' early return?' + : ''); + context.report({ node: hook, message: message }); + } + } + else if (codePathNode.parent != null && + (codePathNode.parent.type === 'MethodDefinition' || + // @ts-expect-error `ClassProperty` was removed from typescript-estree in https://github.com/typescript-eslint/typescript-eslint/pull/3806 + codePathNode.parent.type === 'ClassProperty' || + codePathNode.parent.type === 'PropertyDefinition') && + codePathNode.parent.value === codePathNode) { + // Custom message for hooks inside a class + var message = "React Hook \"".concat(getSourceCode().getText(hook), "\" cannot be called ") + + 'in a class component. React Hooks must be called in a ' + + 'React function component or a custom React Hook function.'; + context.report({ node: hook, message: message }); + } + else if (codePathFunctionName) { + // Custom message if we found an invalid function name. + var message = "React Hook \"".concat(getSourceCode().getText(hook), "\" is called in ") + + "function \"".concat(getSourceCode().getText(codePathFunctionName), "\" ") + + 'that is neither a React function component nor a custom ' + + 'React Hook function.' + + ' React component names must start with an uppercase letter.' + + ' React Hook names must start with the word "use".'; + context.report({ node: hook, message: message }); + } + else if (codePathNode.type === 'Program') { + // These are dangerous if you have inline requires enabled. + var message = "React Hook \"".concat(getSourceCode().getText(hook), "\" cannot be called ") + + 'at the top level. React Hooks must be called in a ' + + 'React function component or a custom React Hook function.'; + context.report({ node: hook, message: message }); + } + else { + // Assume in all other cases the user called a hook in some + // random function callback. This should usually be true for + // anonymous function expressions. Hopefully this is clarifying + // enough in the common case that the incorrect message in + // uncommon cases doesn't matter. + // `use(...)` can be called in callbacks. + if (isSomewhereInsideComponentOrHook && !isUseIdentifier(hook)) { + var message = "React Hook \"".concat(getSourceCode().getText(hook), "\" cannot be called ") + + 'inside a callback. React Hooks must be called in a ' + + 'React function component or a custom React Hook function.'; + context.report({ node: hook, message: message }); + } + } + } + } + catch (e_5_1) { e_5 = { error: e_5_1 }; } + finally { + try { + if (reactHooks_1_1 && !reactHooks_1_1.done && (_c = reactHooks_1.return)) _c.call(reactHooks_1); + } + finally { if (e_5) throw e_5.error; } + } + } + } + catch (e_4_1) { e_4 = { error: e_4_1 }; } + finally { + try { + if (reactHooksMap_1_1 && !reactHooksMap_1_1.done && (_b = reactHooksMap_1.return)) _b.call(reactHooksMap_1); + } + finally { if (e_4) throw e_4.error; } + } + }, + // Missed opportunity...We could visit all `Identifier`s instead of all + // `CallExpression`s and check that _every use_ of a hook name is valid. + // But that gets complicated and enters type-system territory, so we're + // only being strict about hook calls for now. + CallExpression: function (node) { + if (isHook(node.callee)) { + // Add the hook node to a map keyed by the code path segment. We will + // do full code path analysis at the end of our code path. + var reactHooksMap = last(codePathReactHooksMapStack); + var codePathSegment = last(codePathSegmentStack); + var reactHooks = reactHooksMap.get(codePathSegment); + if (!reactHooks) { + reactHooks = []; + reactHooksMap.set(codePathSegment, reactHooks); + } + reactHooks.push(node.callee); + } + // useEffectEvent: useEffectEvent functions can be passed by reference within useEffect as well as in + // another useEffectEvent + if (node.callee.type === 'Identifier' && + (node.callee.name === 'useEffect' || + isUseEffectEventIdentifier$1()) && + node.arguments.length > 0) { + // Denote that we have traversed into a useEffect call, and stash the CallExpr for + // comparison later when we exit + lastEffect = node; + } + }, + Identifier: function (node) { + // This identifier resolves to a useEffectEvent function, but isn't being referenced in an + // effect or another event function. It isn't being called either. + if (lastEffect == null && + useEffectEventFunctions.has(node) && + node.parent.type !== 'CallExpression') { + context.report({ + node: node, + message: "`".concat(getSourceCode().getText(node), "` is a function created with React Hook \"useEffectEvent\", and can only be called from ") + + 'the same component. They cannot be assigned to variables or passed down.', + }); + } + }, + 'CallExpression:exit': function (node) { + if (node === lastEffect) { + lastEffect = null; + } + }, + FunctionDeclaration: function (node) { + // function MyComponent() { const onClick = useEffectEvent(...) } + if (isInsideComponentOrHook(node)) { + recordAllUseEffectEventFunctions(getScope(node)); + } + }, + ArrowFunctionExpression: function (node) { + // const MyComponent = () => { const onClick = useEffectEvent(...) } + if (isInsideComponentOrHook(node)) { + recordAllUseEffectEventFunctions(getScope(node)); + } + }, + }; + }, +}; +/** + * Gets the static name of a function AST node. For function declarations it is + * easy. For anonymous function expressions it is much harder. If you search for + * `IsAnonymousFunctionDefinition()` in the ECMAScript spec you'll find places + * where JS gives anonymous function expressions names. We roughly detect the + * same AST nodes with some exceptions to better fit our use case. + */ +function getFunctionName(node) { + var _a, _b, _c, _d; + if (node.type === 'FunctionDeclaration' || + (node.type === 'FunctionExpression' && node.id)) { + // function useHook() {} + // const whatever = function useHook() {}; + // + // Function declaration or function expression names win over any + // assignment statements or other renames. + return node.id; + } + else if (node.type === 'FunctionExpression' || + node.type === 'ArrowFunctionExpression') { + if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.type) === 'VariableDeclarator' && + node.parent.init === node) { + // const useHook = () => {}; + return node.parent.id; + } + else if (((_b = node.parent) === null || _b === void 0 ? void 0 : _b.type) === 'AssignmentExpression' && + node.parent.right === node && + node.parent.operator === '=') { + // useHook = () => {}; + return node.parent.left; + } + else if (((_c = node.parent) === null || _c === void 0 ? void 0 : _c.type) === 'Property' && + node.parent.value === node && + !node.parent.computed) { + // {useHook: () => {}} + // {useHook() {}} + return node.parent.key; + // NOTE: We could also support `ClassProperty` and `MethodDefinition` + // here to be pedantic. However, hooks in a class are an anti-pattern. So + // we don't allow it to error early. + // + // class {useHook = () => {}} + // class {useHook() {}} + } + else if (((_d = node.parent) === null || _d === void 0 ? void 0 : _d.type) === 'AssignmentPattern' && + node.parent.right === node && + // @ts-expect-error Property computed does not exist on type `AssignmentPattern`. + !node.parent.computed) { + // const {useHook = () => {}} = {}; + // ({useHook = () => {}} = {}); + // + // Kinda clowny, but we'd said we'd follow spec convention for + // `IsAnonymousFunctionDefinition()` usage. + return node.parent.left; + } + else { + return undefined; + } + } + else { + return undefined; + } +} +/** + * Convenience function for peeking the last item in a stack. + */ +function last(array) { + return array[array.length - 1]; +} + +var rule = { + meta: { + type: 'suggestion', + docs: { + description: 'verifies the list of dependencies for Hooks like useEffect and similar', + recommended: true, + url: 'https://github.com/facebook/react/issues/14920', + }, + fixable: 'code', + hasSuggestions: true, + schema: [ + { + type: 'object', + additionalProperties: false, + enableDangerousAutofixThisMayCauseInfiniteLoops: false, + properties: { + additionalHooks: { + type: 'string', + }, + enableDangerousAutofixThisMayCauseInfiniteLoops: { + type: 'boolean', + }, + }, + }, + ], + }, + create: function (context) { + // Parse the `additionalHooks` regex. + var additionalHooks = context.options && + context.options[0] && + context.options[0].additionalHooks + ? new RegExp(context.options[0].additionalHooks) + : undefined; + var enableDangerousAutofixThisMayCauseInfiniteLoops = (context.options && + context.options[0] && + context.options[0].enableDangerousAutofixThisMayCauseInfiniteLoops) || + false; + var options = { + additionalHooks: additionalHooks, + enableDangerousAutofixThisMayCauseInfiniteLoops: enableDangerousAutofixThisMayCauseInfiniteLoops, + }; + function reportProblem(problem) { + if (enableDangerousAutofixThisMayCauseInfiniteLoops) { + // Used to enable legacy behavior. Dangerous. + // Keep this as an option until major IDEs upgrade (including VSCode FB ESLint extension). + if (Array.isArray(problem.suggest) && + problem.suggest.length > 0 && + problem.suggest[0]) { + problem.fix = problem.suggest[0].fix; + } + } + context.report(problem); + } + /** + * SourceCode that also works down to ESLint 3.0.0 + */ + var getSourceCode = typeof context.getSourceCode === 'function' + ? function () { + return context.getSourceCode(); + } + : function () { + return context.sourceCode; + }; + /** + * SourceCode#getScope that also works down to ESLint 3.0.0 + */ + var getScope = typeof context.getScope === 'function' + ? function () { + return context.getScope(); + } + : function (node) { + return context.sourceCode.getScope(node); + }; + var scopeManager = getSourceCode().scopeManager; + // Should be shared between visitors. + var setStateCallSites = new WeakMap(); + var stateVariables = new WeakSet(); + var stableKnownValueCache = new WeakMap(); + var functionWithoutCapturedValueCache = new WeakMap(); + var useEffectEventVariables = new WeakSet(); + function memoizeWithWeakMap(fn, map) { + return function (arg) { + if (map.has(arg)) { + // to verify cache hits: + // console.log(arg.name) + return map.get(arg); + } + var result = fn(arg); + map.set(arg, result); + return result; + }; + } + /** + * Visitor for both function expressions and arrow function expressions. + */ + function visitFunctionWithDependencies(node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect) { + var e_1, _a, e_2, _b, e_3, _c; + if (isEffect && node.async) { + reportProblem({ + node: node, + message: "Effect callbacks are synchronous to prevent race conditions. " + + "Put the async function inside:\n\n" + + 'useEffect(() => {\n' + + ' async function fetchData() {\n' + + ' // You can await here\n' + + ' const response = await MyAPI.getData(someId);\n' + + ' // ...\n' + + ' }\n' + + ' fetchData();\n' + + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + + 'Learn more about data fetching with Hooks: https://react.dev/link/hooks-data-fetching', + }); + } + // Get the current scope. + var scope = scopeManager.acquire(node); + if (!scope) { + throw new Error('Unable to acquire scope for the current node. This is a bug in eslint-plugin-react-hooks, please file an issue.'); + } + // Find all our "pure scopes". On every re-render of a component these + // pure scopes may have changes to the variables declared within. So all + // variables used in our reactive hook callback but declared in a pure + // scope need to be listed as dependencies of our reactive hook callback. + // + // According to the rules of React you can't read a mutable value in pure + // scope. We can't enforce this in a lint so we trust that all variables + // declared outside of pure scope are indeed frozen. + var pureScopes = new Set(); + var componentScope = null; + { + var currentScope = scope.upper; + while (currentScope) { + pureScopes.add(currentScope); + if (currentScope.type === 'function') { + break; + } + currentScope = currentScope.upper; + } + // If there is no parent function scope then there are no pure scopes. + // The ones we've collected so far are incorrect. So don't continue with + // the lint. + if (!currentScope) { + return; + } + componentScope = currentScope; + } + var isArray = Array.isArray; + // Next we'll define a few helpers that helps us + // tell if some values don't have to be declared as deps. + // Some are known to be stable based on Hook calls. + // const [state, setState] = useState() / React.useState() + // ^^^ true for this reference + // const [state, dispatch] = useReducer() / React.useReducer() + // ^^^ true for this reference + // const [state, dispatch] = useActionState() / React.useActionState() + // ^^^ true for this reference + // const ref = useRef() + // ^^^ true for this reference + // const onStuff = useEffectEvent(() => {}) + // ^^^ true for this reference + // False for everything else. + function isStableKnownHookValue(resolved) { + var e_4, _a, e_5, _b, e_6, _c; + if (!isArray(resolved.defs)) { + return false; + } + var def = resolved.defs[0]; + if (def == null) { + return false; + } + // Look for `let stuff = ...` + var defNode = def.node; + if (defNode.type !== 'VariableDeclarator') { + return false; + } + var init = defNode.init; + if (init == null) { + return false; + } + while (init.type === 'TSAsExpression' || init.type === 'AsExpression') { + init = init.expression; + } + // Detect primitive constants + // const foo = 42 + var declaration = defNode.parent; + if (declaration == null && componentScope != null) { + // This might happen if variable is declared after the callback. + // In that case ESLint won't set up .parent refs. + // So we'll set them up manually. + fastFindReferenceWithParent(componentScope.block, def.node.id); + declaration = def.node.parent; + if (declaration == null) { + return false; + } + } + if (declaration != null && + 'kind' in declaration && + declaration.kind === 'const' && + init.type === 'Literal' && + (typeof init.value === 'string' || + typeof init.value === 'number' || + init.value === null)) { + // Definitely stable + return true; + } + // Detect known Hook calls + // const [_, setState] = useState() + if (init.type !== 'CallExpression') { + return false; + } + var callee = init.callee; + // Step into `= React.something` initializer. + if (callee.type === 'MemberExpression' && + 'name' in callee.object && + callee.object.name === 'React' && + callee.property != null && + !callee.computed) { + callee = callee.property; + } + if (callee.type !== 'Identifier') { + return false; + } + var definitionNode = def.node; + var id = definitionNode.id; + var name = callee.name; + if (name === 'useRef' && id.type === 'Identifier') { + // useRef() return value is stable. + return true; + } + else if (isUseEffectEventIdentifier() && + id.type === 'Identifier') { + try { + for (var _d = __values(resolved.references), _e = _d.next(); !_e.done; _e = _d.next()) { + var ref = _e.value; + // @ts-expect-error These types are not compatible (Reference and Identifier) + if (ref !== id) { + useEffectEventVariables.add(ref.identifier); + } + } + } + catch (e_4_1) { e_4 = { error: e_4_1 }; } + finally { + try { + if (_e && !_e.done && (_a = _d.return)) _a.call(_d); + } + finally { if (e_4) throw e_4.error; } + } + // useEffectEvent() return value is always unstable. + return true; + } + else if (name === 'useState' || + name === 'useReducer' || + name === 'useActionState') { + // Only consider second value in initializing tuple stable. + if (id.type === 'ArrayPattern' && + id.elements.length === 2 && + isArray(resolved.identifiers)) { + // Is second tuple value the same reference we're checking? + if (id.elements[1] === resolved.identifiers[0]) { + if (name === 'useState') { + var references = resolved.references; + var writeCount = 0; + try { + for (var references_2 = __values(references), references_2_1 = references_2.next(); !references_2_1.done; references_2_1 = references_2.next()) { + var reference = references_2_1.value; + if (reference.isWrite()) { + writeCount++; + } + if (writeCount > 1) { + return false; + } + setStateCallSites.set(reference.identifier, id.elements[0]); + } + } + catch (e_5_1) { e_5 = { error: e_5_1 }; } + finally { + try { + if (references_2_1 && !references_2_1.done && (_b = references_2.return)) _b.call(references_2); + } + finally { if (e_5) throw e_5.error; } + } + } + // Setter is stable. + return true; + } + else if (id.elements[0] === resolved.identifiers[0]) { + if (name === 'useState') { + var references = resolved.references; + try { + for (var references_3 = __values(references), references_3_1 = references_3.next(); !references_3_1.done; references_3_1 = references_3.next()) { + var reference = references_3_1.value; + stateVariables.add(reference.identifier); + } + } + catch (e_6_1) { e_6 = { error: e_6_1 }; } + finally { + try { + if (references_3_1 && !references_3_1.done && (_c = references_3.return)) _c.call(references_3); + } + finally { if (e_6) throw e_6.error; } + } + } + // State variable itself is dynamic. + return false; + } + } + } + else if (name === 'useTransition') { + // Only consider second value in initializing tuple stable. + if (id.type === 'ArrayPattern' && + id.elements.length === 2 && + Array.isArray(resolved.identifiers)) { + // Is second tuple value the same reference we're checking? + if (id.elements[1] === resolved.identifiers[0]) { + // Setter is stable. + return true; + } + } + } + // By default assume it's dynamic. + return false; + } + // Some are just functions that don't reference anything dynamic. + function isFunctionWithoutCapturedValues(resolved) { + var e_7, _a, e_8, _b; + if (!isArray(resolved.defs)) { + return false; + } + var def = resolved.defs[0]; + if (def == null) { + return false; + } + if (def.node == null || def.node.id == null) { + return false; + } + // Search the direct component subscopes for + // top-level function definitions matching this reference. + var fnNode = def.node; + var childScopes = (componentScope === null || componentScope === void 0 ? void 0 : componentScope.childScopes) || []; + var fnScope = null; + try { + for (var childScopes_1 = __values(childScopes), childScopes_1_1 = childScopes_1.next(); !childScopes_1_1.done; childScopes_1_1 = childScopes_1.next()) { + var childScope = childScopes_1_1.value; + var childScopeBlock = childScope.block; + if ( + // function handleChange() {} + (fnNode.type === 'FunctionDeclaration' && + childScopeBlock === fnNode) || + // const handleChange = () => {} + // const handleChange = function() {} + (fnNode.type === 'VariableDeclarator' && + childScopeBlock.parent === fnNode)) { + // Found it! + fnScope = childScope; + break; + } + } + } + catch (e_7_1) { e_7 = { error: e_7_1 }; } + finally { + try { + if (childScopes_1_1 && !childScopes_1_1.done && (_a = childScopes_1.return)) _a.call(childScopes_1); + } + finally { if (e_7) throw e_7.error; } + } + if (fnScope == null) { + return false; + } + try { + // Does this function capture any values + // that are in pure scopes (aka render)? + for (var _c = __values(fnScope.through), _d = _c.next(); !_d.done; _d = _c.next()) { + var ref = _d.value; + if (ref.resolved == null) { + continue; + } + if (pureScopes.has(ref.resolved.scope) && + // Stable values are fine though, + // although we won't check functions deeper. + !memoizedIsStableKnownHookValue(ref.resolved)) { + return false; + } + } + } + catch (e_8_1) { e_8 = { error: e_8_1 }; } + finally { + try { + if (_d && !_d.done && (_b = _c.return)) _b.call(_c); + } + finally { if (e_8) throw e_8.error; } + } + // If we got here, this function doesn't capture anything + // from render--or everything it captures is known stable. + return true; + } + // Remember such values. Avoid re-running extra checks on them. + var memoizedIsStableKnownHookValue = memoizeWithWeakMap(isStableKnownHookValue, stableKnownValueCache); + var memoizedIsFunctionWithoutCapturedValues = memoizeWithWeakMap(isFunctionWithoutCapturedValues, functionWithoutCapturedValueCache); + // These are usually mistaken. Collect them. + var currentRefsInEffectCleanup = new Map(); + // Is this reference inside a cleanup function for this effect node? + // We can check by traversing scopes upwards from the reference, and checking + // if the last "return () => " we encounter is located directly inside the effect. + function isInsideEffectCleanup(reference) { + var curScope = reference.from; + var isInReturnedFunction = false; + while (curScope != null && curScope.block !== node) { + if (curScope.type === 'function') { + isInReturnedFunction = + curScope.block.parent != null && + curScope.block.parent.type === 'ReturnStatement'; + } + curScope = curScope.upper; + } + return isInReturnedFunction; + } + // Get dependencies from all our resolved references in pure scopes. + // Key is dependency string, value is whether it's stable. + var dependencies = new Map(); + var optionalChains = new Map(); + gatherDependenciesRecursively(scope); + function gatherDependenciesRecursively(currentScope) { + var e_9, _a, e_10, _b; + var _c, _d, _e, _f, _g; + try { + for (var _h = __values(currentScope.references), _j = _h.next(); !_j.done; _j = _h.next()) { + var reference = _j.value; + // If this reference is not resolved or it is not declared in a pure + // scope then we don't care about this reference. + if (!reference.resolved) { + continue; + } + if (!pureScopes.has(reference.resolved.scope)) { + continue; + } + // Narrow the scope of a dependency if it is, say, a member expression. + // Then normalize the narrowed dependency. + var referenceNode = fastFindReferenceWithParent(node, reference.identifier); + if (referenceNode == null) { + continue; + } + var dependencyNode = getDependency(referenceNode); + var dependency = analyzePropertyChain(dependencyNode, optionalChains); + // Accessing ref.current inside effect cleanup is bad. + if ( + // We're in an effect... + isEffect && + // ... and this look like accessing .current... + dependencyNode.type === 'Identifier' && + (((_c = dependencyNode.parent) === null || _c === void 0 ? void 0 : _c.type) === 'MemberExpression' || + ((_d = dependencyNode.parent) === null || _d === void 0 ? void 0 : _d.type) === 'OptionalMemberExpression') && + !dependencyNode.parent.computed && + dependencyNode.parent.property.type === 'Identifier' && + dependencyNode.parent.property.name === 'current' && + // ...in a cleanup function or below... + isInsideEffectCleanup(reference)) { + currentRefsInEffectCleanup.set(dependency, { + reference: reference, + dependencyNode: dependencyNode, + }); + } + if (((_e = dependencyNode.parent) === null || _e === void 0 ? void 0 : _e.type) === 'TSTypeQuery' || + ((_f = dependencyNode.parent) === null || _f === void 0 ? void 0 : _f.type) === 'TSTypeReference') { + continue; + } + var def = reference.resolved.defs[0]; + if (def == null) { + continue; + } + // Ignore references to the function itself as it's not defined yet. + if (def.node != null && def.node.init === node.parent) { + continue; + } + // Ignore Flow type parameters + // @ts-expect-error We don't have flow types + if (def.type === 'TypeParameter') { + continue; + } + // Add the dependency to a map so we can make sure it is referenced + // again in our dependencies array. Remember whether it's stable. + if (!dependencies.has(dependency)) { + var resolved = reference.resolved; + var isStable = memoizedIsStableKnownHookValue(resolved) || + memoizedIsFunctionWithoutCapturedValues(resolved); + dependencies.set(dependency, { + isStable: isStable, + references: [reference], + }); + } + else { + (_g = dependencies.get(dependency)) === null || _g === void 0 ? void 0 : _g.references.push(reference); + } + } + } + catch (e_9_1) { e_9 = { error: e_9_1 }; } + finally { + try { + if (_j && !_j.done && (_a = _h.return)) _a.call(_h); + } + finally { if (e_9) throw e_9.error; } + } + try { + for (var _k = __values(currentScope.childScopes), _l = _k.next(); !_l.done; _l = _k.next()) { + var childScope = _l.value; + gatherDependenciesRecursively(childScope); + } + } + catch (e_10_1) { e_10 = { error: e_10_1 }; } + finally { + try { + if (_l && !_l.done && (_b = _k.return)) _b.call(_k); + } + finally { if (e_10) throw e_10.error; } + } + } + // Warn about accessing .current in cleanup effects. + currentRefsInEffectCleanup.forEach(function (_a, dependency) { + var e_11, _b; + var _c, _d; + var reference = _a.reference, dependencyNode = _a.dependencyNode; + var references = ((_c = reference.resolved) === null || _c === void 0 ? void 0 : _c.references) || []; + // Is React managing this ref or us? + // Let's see if we can find a .current assignment. + var foundCurrentAssignment = false; + try { + for (var references_4 = __values(references), references_4_1 = references_4.next(); !references_4_1.done; references_4_1 = references_4.next()) { + var ref = references_4_1.value; + var identifier = ref.identifier; + var parent = identifier.parent; + if (parent != null && + // ref.current + // Note: no need to handle OptionalMemberExpression because it can't be LHS. + parent.type === 'MemberExpression' && + !parent.computed && + parent.property.type === 'Identifier' && + parent.property.name === 'current' && + // ref.current = + ((_d = parent.parent) === null || _d === void 0 ? void 0 : _d.type) === 'AssignmentExpression' && + parent.parent.left === parent) { + foundCurrentAssignment = true; + break; + } + } + } + catch (e_11_1) { e_11 = { error: e_11_1 }; } + finally { + try { + if (references_4_1 && !references_4_1.done && (_b = references_4.return)) _b.call(references_4); + } + finally { if (e_11) throw e_11.error; } + } + // We only want to warn about React-managed refs. + if (foundCurrentAssignment) { + return; + } + reportProblem({ + // @ts-expect-error We can do better here (dependencyNode.parent has not been type narrowed) + node: dependencyNode.parent.property, + message: "The ref value '".concat(dependency, ".current' will likely have ") + + "changed by the time this effect cleanup function runs. If " + + "this ref points to a node rendered by React, copy " + + "'".concat(dependency, ".current' to a variable inside the effect, and ") + + "use that variable in the cleanup function.", + }); + }); + // Warn about assigning to variables in the outer scope. + // Those are usually bugs. + var staleAssignments = new Set(); + function reportStaleAssignment(writeExpr, key) { + if (staleAssignments.has(key)) { + return; + } + staleAssignments.add(key); + reportProblem({ + node: writeExpr, + message: "Assignments to the '".concat(key, "' variable from inside React Hook ") + + "".concat(getSourceCode().getText(reactiveHook), " will be lost after each ") + + "render. To preserve the value over time, store it in a useRef " + + "Hook and keep the mutable value in the '.current' property. " + + "Otherwise, you can move this variable directly inside " + + "".concat(getSourceCode().getText(reactiveHook), "."), + }); + } + // Remember which deps are stable and report bad usage first. + var stableDependencies = new Set(); + dependencies.forEach(function (_a, key) { + var isStable = _a.isStable, references = _a.references; + if (isStable) { + stableDependencies.add(key); + } + references.forEach(function (reference) { + if (reference.writeExpr) { + reportStaleAssignment(reference.writeExpr, key); + } + }); + }); + if (staleAssignments.size > 0) { + // The intent isn't clear so we'll wait until you fix those first. + return; + } + if (!declaredDependenciesNode) { + // Check if there are any top-level setState() calls. + // Those tend to lead to infinite loops. + var setStateInsideEffectWithoutDeps_1 = null; + dependencies.forEach(function (_a, key) { + var references = _a.references; + if (setStateInsideEffectWithoutDeps_1) { + return; + } + references.forEach(function (reference) { + if (setStateInsideEffectWithoutDeps_1) { + return; + } + var id = reference.identifier; + var isSetState = setStateCallSites.has(id); + if (!isSetState) { + return; + } + var fnScope = reference.from; + while (fnScope != null && fnScope.type !== 'function') { + fnScope = fnScope.upper; + } + var isDirectlyInsideEffect = (fnScope === null || fnScope === void 0 ? void 0 : fnScope.block) === node; + if (isDirectlyInsideEffect) { + // TODO: we could potentially ignore early returns. + setStateInsideEffectWithoutDeps_1 = key; + } + }); + }); + if (setStateInsideEffectWithoutDeps_1) { + var suggestedDependencies_1 = collectRecommendations({ + dependencies: dependencies, + declaredDependencies: [], + stableDependencies: stableDependencies, + externalDependencies: new Set(), + isEffect: true, + }).suggestedDependencies; + reportProblem({ + node: reactiveHook, + message: "React Hook ".concat(reactiveHookName, " contains a call to '").concat(setStateInsideEffectWithoutDeps_1, "'. ") + + "Without a list of dependencies, this can lead to an infinite chain of updates. " + + "To fix this, pass [" + + suggestedDependencies_1.join(', ') + + "] as a second argument to the ".concat(reactiveHookName, " Hook."), + suggest: [ + { + desc: "Add dependencies array: [".concat(suggestedDependencies_1.join(', '), "]"), + fix: function (fixer) { + return fixer.insertTextAfter(node, ", [".concat(suggestedDependencies_1.join(', '), "]")); + }, + }, + ], + }); + } + return; + } + var declaredDependencies = []; + var externalDependencies = new Set(); + var isArrayExpression = declaredDependenciesNode.type === 'ArrayExpression'; + var isTSAsArrayExpression = declaredDependenciesNode.type === 'TSAsExpression' && + declaredDependenciesNode.expression.type === 'ArrayExpression'; + if (!isArrayExpression && !isTSAsArrayExpression) { + // If the declared dependencies are not an array expression then we + // can't verify that the user provided the correct dependencies. Tell + // the user this in an error. + reportProblem({ + node: declaredDependenciesNode, + message: "React Hook ".concat(getSourceCode().getText(reactiveHook), " was passed a ") + + 'dependency list that is not an array literal. This means we ' + + "can't statically verify whether you've passed the correct " + + 'dependencies.', + }); + } + else { + var arrayExpression = isTSAsArrayExpression + ? declaredDependenciesNode.expression + : declaredDependenciesNode; + arrayExpression.elements.forEach(function (declaredDependencyNode) { + // Skip elided elements. + if (declaredDependencyNode === null) { + return; + } + // If we see a spread element then add a special warning. + if (declaredDependencyNode.type === 'SpreadElement') { + reportProblem({ + node: declaredDependencyNode, + message: "React Hook ".concat(getSourceCode().getText(reactiveHook), " has a spread ") + + "element in its dependency array. This means we can't " + + "statically verify whether you've passed the " + + 'correct dependencies.', + }); + return; + } + if (useEffectEventVariables.has(declaredDependencyNode)) { + reportProblem({ + node: declaredDependencyNode, + message: 'Functions returned from `useEffectEvent` must not be included in the dependency array. ' + + "Remove `".concat(getSourceCode().getText(declaredDependencyNode), "` from the list."), + suggest: [ + { + desc: "Remove the dependency `".concat(getSourceCode().getText(declaredDependencyNode), "`"), + fix: function (fixer) { + return fixer.removeRange(declaredDependencyNode.range); + }, + }, + ], + }); + } + // Try to normalize the declared dependency. If we can't then an error + // will be thrown. We will catch that error and report an error. + var declaredDependency; + try { + declaredDependency = analyzePropertyChain(declaredDependencyNode, null); + } + catch (error) { + if (error instanceof Error && + /Unsupported node type/.test(error.message)) { + if (declaredDependencyNode.type === 'Literal') { + if (declaredDependencyNode.value && + dependencies.has(declaredDependencyNode.value)) { + reportProblem({ + node: declaredDependencyNode, + message: "The ".concat(declaredDependencyNode.raw, " literal is not a valid dependency ") + + "because it never changes. " + + "Did you mean to include ".concat(declaredDependencyNode.value, " in the array instead?"), + }); + } + else { + reportProblem({ + node: declaredDependencyNode, + message: "The ".concat(declaredDependencyNode.raw, " literal is not a valid dependency ") + + 'because it never changes. You can safely remove it.', + }); + } + } + else { + reportProblem({ + node: declaredDependencyNode, + message: "React Hook ".concat(getSourceCode().getText(reactiveHook), " has a ") + + "complex expression in the dependency array. " + + 'Extract it to a separate variable so it can be statically checked.', + }); + } + return; + } + else { + throw error; + } + } + var maybeID = declaredDependencyNode; + while (maybeID.type === 'MemberExpression' || + maybeID.type === 'OptionalMemberExpression' || + maybeID.type === 'ChainExpression') { + // @ts-expect-error This can be done better + maybeID = maybeID.object || maybeID.expression.object; + } + var isDeclaredInComponent = !componentScope.through.some(function (ref) { return ref.identifier === maybeID; }); + // Add the dependency to our declared dependency map. + declaredDependencies.push({ + key: declaredDependency, + node: declaredDependencyNode, + }); + if (!isDeclaredInComponent) { + externalDependencies.add(declaredDependency); + } + }); + } + var _d = collectRecommendations({ + dependencies: dependencies, + declaredDependencies: declaredDependencies, + stableDependencies: stableDependencies, + externalDependencies: externalDependencies, + isEffect: isEffect, + }), suggestedDependencies = _d.suggestedDependencies, unnecessaryDependencies = _d.unnecessaryDependencies, missingDependencies = _d.missingDependencies, duplicateDependencies = _d.duplicateDependencies; + var suggestedDeps = suggestedDependencies; + var problemCount = duplicateDependencies.size + + missingDependencies.size + + unnecessaryDependencies.size; + if (problemCount === 0) { + // If nothing else to report, check if some dependencies would + // invalidate on every render. + var constructions = scanForConstructions({ + declaredDependencies: declaredDependencies, + declaredDependenciesNode: declaredDependenciesNode, + componentScope: componentScope, + scope: scope, + }); + constructions.forEach(function (_a) { + var _b; + var construction = _a.construction, isUsedOutsideOfHook = _a.isUsedOutsideOfHook, depType = _a.depType; + var wrapperHook = depType === 'function' ? 'useCallback' : 'useMemo'; + var constructionType = depType === 'function' ? 'definition' : 'initialization'; + var defaultAdvice = "wrap the ".concat(constructionType, " of '").concat(construction.name.name, "' in its own ").concat(wrapperHook, "() Hook."); + var advice = isUsedOutsideOfHook + ? "To fix this, ".concat(defaultAdvice) + : "Move it inside the ".concat(reactiveHookName, " callback. Alternatively, ").concat(defaultAdvice); + var causation = depType === 'conditional' || depType === 'logical expression' + ? 'could make' + : 'makes'; + var message = "The '".concat(construction.name.name, "' ").concat(depType, " ").concat(causation, " the dependencies of ") + + "".concat(reactiveHookName, " Hook (at line ").concat((_b = declaredDependenciesNode.loc) === null || _b === void 0 ? void 0 : _b.start.line, ") ") + + "change on every render. ".concat(advice); + var suggest; + // Only handle the simple case of variable assignments. + // Wrapping function declarations can mess up hoisting. + if (isUsedOutsideOfHook && + construction.type === 'Variable' && + // Objects may be mutated after construction, which would make this + // fix unsafe. Functions _probably_ won't be mutated, so we'll + // allow this fix for them. + depType === 'function') { + suggest = [ + { + desc: "Wrap the ".concat(constructionType, " of '").concat(construction.name.name, "' in its own ").concat(wrapperHook, "() Hook."), + fix: function (fixer) { + var _a = __read(wrapperHook === 'useMemo' + ? ["useMemo(() => { return ", '; })'] + : ['useCallback(', ')'], 2), before = _a[0], after = _a[1]; + return [ + // TODO: also add an import? + fixer.insertTextBefore(construction.node.init, before), + // TODO: ideally we'd gather deps here but it would require + // restructuring the rule code. This will cause a new lint + // error to appear immediately for useCallback. Note we're + // not adding [] because would that changes semantics. + fixer.insertTextAfter(construction.node.init, after), + ]; + }, + }, + ]; + } + // TODO: What if the function needs to change on every render anyway? + // Should we suggest removing effect deps as an appropriate fix too? + reportProblem({ + // TODO: Why not report this at the dependency site? + node: construction.node, + message: message, + suggest: suggest, + }); + }); + return; + } + // If we're going to report a missing dependency, + // we might as well recalculate the list ignoring + // the currently specified deps. This can result + // in some extra deduplication. We can't do this + // for effects though because those have legit + // use cases for over-specifying deps. + if (!isEffect && missingDependencies.size > 0) { + suggestedDeps = collectRecommendations({ + dependencies: dependencies, + declaredDependencies: [], // Pretend we don't know + stableDependencies: stableDependencies, + externalDependencies: externalDependencies, + isEffect: isEffect, + }).suggestedDependencies; + } + // Alphabetize the suggestions, but only if deps were already alphabetized. + function areDeclaredDepsAlphabetized() { + if (declaredDependencies.length === 0) { + return true; + } + var declaredDepKeys = declaredDependencies.map(function (dep) { return dep.key; }); + var sortedDeclaredDepKeys = declaredDepKeys.slice().sort(); + return declaredDepKeys.join(',') === sortedDeclaredDepKeys.join(','); + } + if (areDeclaredDepsAlphabetized()) { + suggestedDeps.sort(); + } + // Most of our algorithm deals with dependency paths with optional chaining stripped. + // This function is the last step before printing a dependency, so now is a good time to + // check whether any members in our path are always used as optional-only. In that case, + // we will use ?. instead of . to concatenate those parts of the path. + function formatDependency(path) { + var members = path.split('.'); + var finalPath = ''; + for (var i = 0; i < members.length; i++) { + if (i !== 0) { + var pathSoFar = members.slice(0, i + 1).join('.'); + var isOptional = optionalChains.get(pathSoFar) === true; + finalPath += isOptional ? '?.' : '.'; + } + finalPath += members[i]; + } + return finalPath; + } + function getWarningMessage(deps, singlePrefix, label, fixVerb) { + if (deps.size === 0) { + return null; + } + return ((deps.size > 1 ? '' : singlePrefix + ' ') + + label + + ' ' + + (deps.size > 1 ? 'dependencies' : 'dependency') + + ': ' + + joinEnglish(Array.from(deps) + .sort() + .map(function (name) { return "'" + formatDependency(name) + "'"; })) + + ". Either ".concat(fixVerb, " ").concat(deps.size > 1 ? 'them' : 'it', " or remove the dependency array.")); + } + var extraWarning = ''; + if (unnecessaryDependencies.size > 0) { + var badRef_1 = null; + Array.from(unnecessaryDependencies.keys()).forEach(function (key) { + if (badRef_1 !== null) { + return; + } + if (key.endsWith('.current')) { + badRef_1 = key; + } + }); + if (badRef_1 !== null) { + extraWarning = + " Mutable values like '".concat(badRef_1, "' aren't valid dependencies ") + + "because mutating them doesn't re-render the component."; + } + else if (externalDependencies.size > 0) { + var dep = Array.from(externalDependencies)[0]; + // Don't show this warning for things that likely just got moved *inside* the callback + // because in that case they're clearly not referring to globals. + if (!scope.set.has(dep)) { + extraWarning = + " Outer scope values like '".concat(dep, "' aren't valid dependencies ") + + "because mutating them doesn't re-render the component."; + } + } + } + // `props.foo()` marks `props` as a dependency because it has + // a `this` value. This warning can be confusing. + // So if we're going to show it, append a clarification. + if (!extraWarning && missingDependencies.has('props')) { + var propDep = dependencies.get('props'); + if (propDep == null) { + return; + } + var refs = propDep.references; + if (!Array.isArray(refs)) { + return; + } + var isPropsOnlyUsedInMembers = true; + try { + for (var refs_1 = __values(refs), refs_1_1 = refs_1.next(); !refs_1_1.done; refs_1_1 = refs_1.next()) { + var ref = refs_1_1.value; + var id = fastFindReferenceWithParent(componentScope.block, ref.identifier); + if (!id) { + isPropsOnlyUsedInMembers = false; + break; + } + var parent = id.parent; + if (parent == null) { + isPropsOnlyUsedInMembers = false; + break; + } + if (parent.type !== 'MemberExpression' && + parent.type !== 'OptionalMemberExpression') { + isPropsOnlyUsedInMembers = false; + break; + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (refs_1_1 && !refs_1_1.done && (_a = refs_1.return)) _a.call(refs_1); + } + finally { if (e_1) throw e_1.error; } + } + if (isPropsOnlyUsedInMembers) { + extraWarning = + " However, 'props' will change when *any* prop changes, so the " + + "preferred fix is to destructure the 'props' object outside of " + + "the ".concat(reactiveHookName, " call and refer to those specific props ") + + "inside ".concat(getSourceCode().getText(reactiveHook), "."); + } + } + if (!extraWarning && missingDependencies.size > 0) { + // See if the user is trying to avoid specifying a callable prop. + // This usually means they're unaware of useCallback. + var missingCallbackDep_1 = null; + missingDependencies.forEach(function (missingDep) { + var e_12, _a; + var _b; + if (missingCallbackDep_1) { + return; + } + // Is this a variable from top scope? + var topScopeRef = componentScope.set.get(missingDep); + var usedDep = dependencies.get(missingDep); + if (!(usedDep === null || usedDep === void 0 ? void 0 : usedDep.references) || + ((_b = usedDep === null || usedDep === void 0 ? void 0 : usedDep.references[0]) === null || _b === void 0 ? void 0 : _b.resolved) !== topScopeRef) { + return; + } + // Is this a destructured prop? + var def = topScopeRef === null || topScopeRef === void 0 ? void 0 : topScopeRef.defs[0]; + if (def == null || def.name == null || def.type !== 'Parameter') { + return; + } + // Was it called in at least one case? Then it's a function. + var isFunctionCall = false; + var id; + try { + for (var _c = __values(usedDep.references), _d = _c.next(); !_d.done; _d = _c.next()) { + var reference = _d.value; + id = reference.identifier; + if (id != null && + id.parent != null && + (id.parent.type === 'CallExpression' || + id.parent.type === 'OptionalCallExpression') && + id.parent.callee === id) { + isFunctionCall = true; + break; + } + } + } + catch (e_12_1) { e_12 = { error: e_12_1 }; } + finally { + try { + if (_d && !_d.done && (_a = _c.return)) _a.call(_c); + } + finally { if (e_12) throw e_12.error; } + } + if (!isFunctionCall) { + return; + } + // If it's missing (i.e. in component scope) *and* it's a parameter + // then it is definitely coming from props destructuring. + // (It could also be props itself but we wouldn't be calling it then.) + missingCallbackDep_1 = missingDep; + }); + if (missingCallbackDep_1 !== null) { + extraWarning = + " If '".concat(missingCallbackDep_1, "' changes too often, ") + + "find the parent component that defines it " + + "and wrap that definition in useCallback."; + } + } + if (!extraWarning && missingDependencies.size > 0) { + var setStateRecommendation = null; + try { + for (var missingDependencies_1 = __values(missingDependencies), missingDependencies_1_1 = missingDependencies_1.next(); !missingDependencies_1_1.done; missingDependencies_1_1 = missingDependencies_1.next()) { + var missingDep = missingDependencies_1_1.value; + if (setStateRecommendation !== null) { + break; + } + var usedDep = dependencies.get(missingDep); + var references = usedDep.references; + var id = void 0; + var maybeCall = void 0; + try { + for (var references_1 = (e_3 = void 0, __values(references)), references_1_1 = references_1.next(); !references_1_1.done; references_1_1 = references_1.next()) { + var reference = references_1_1.value; + id = reference.identifier; + maybeCall = id.parent; + // Try to see if we have setState(someExpr(missingDep)). + while (maybeCall != null && maybeCall !== componentScope.block) { + if (maybeCall.type === 'CallExpression') { + var correspondingStateVariable = setStateCallSites.get(maybeCall.callee); + if (correspondingStateVariable != null) { + if ('name' in correspondingStateVariable && + correspondingStateVariable.name === missingDep) { + // setCount(count + 1) + setStateRecommendation = { + missingDep: missingDep, + setter: 'name' in maybeCall.callee ? maybeCall.callee.name : '', + form: 'updater', + }; + } + else if (stateVariables.has(id)) { + // setCount(count + increment) + setStateRecommendation = { + missingDep: missingDep, + setter: 'name' in maybeCall.callee ? maybeCall.callee.name : '', + form: 'reducer', + }; + } + else { + var resolved = reference.resolved; + if (resolved != null) { + // If it's a parameter *and* a missing dep, + // it must be a prop or something inside a prop. + // Therefore, recommend an inline reducer. + var def = resolved.defs[0]; + if (def != null && def.type === 'Parameter') { + setStateRecommendation = { + missingDep: missingDep, + setter: 'name' in maybeCall.callee + ? maybeCall.callee.name + : '', + form: 'inlineReducer', + }; + } + } + } + break; + } + } + maybeCall = maybeCall.parent; + } + if (setStateRecommendation !== null) { + break; + } + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (references_1_1 && !references_1_1.done && (_c = references_1.return)) _c.call(references_1); + } + finally { if (e_3) throw e_3.error; } + } + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (missingDependencies_1_1 && !missingDependencies_1_1.done && (_b = missingDependencies_1.return)) _b.call(missingDependencies_1); + } + finally { if (e_2) throw e_2.error; } + } + if (setStateRecommendation !== null) { + switch (setStateRecommendation.form) { + case 'reducer': + extraWarning = + " You can also replace multiple useState variables with useReducer " + + "if '".concat(setStateRecommendation.setter, "' needs the ") + + "current value of '".concat(setStateRecommendation.missingDep, "'."); + break; + case 'inlineReducer': + extraWarning = + " If '".concat(setStateRecommendation.setter, "' needs the ") + + "current value of '".concat(setStateRecommendation.missingDep, "', ") + + "you can also switch to useReducer instead of useState and " + + "read '".concat(setStateRecommendation.missingDep, "' in the reducer."); + break; + case 'updater': + extraWarning = + " You can also do a functional update '".concat(setStateRecommendation.setter, "(").concat(setStateRecommendation.missingDep.slice(0, 1), " => ...)' if you only need '").concat(setStateRecommendation.missingDep, "'") + " in the '".concat(setStateRecommendation.setter, "' call."); + break; + default: + throw new Error('Unknown case.'); + } + } + } + reportProblem({ + node: declaredDependenciesNode, + message: "React Hook ".concat(getSourceCode().getText(reactiveHook), " has ") + + // To avoid a long message, show the next actionable item. + (getWarningMessage(missingDependencies, 'a', 'missing', 'include') || + getWarningMessage(unnecessaryDependencies, 'an', 'unnecessary', 'exclude') || + getWarningMessage(duplicateDependencies, 'a', 'duplicate', 'omit')) + + extraWarning, + suggest: [ + { + desc: "Update the dependencies array to be: [".concat(suggestedDeps + .map(formatDependency) + .join(', '), "]"), + fix: function (fixer) { + // TODO: consider preserving the comments or formatting? + return fixer.replaceText(declaredDependenciesNode, "[".concat(suggestedDeps.map(formatDependency).join(', '), "]")); + }, + }, + ], + }); + } + function visitCallExpression(node) { + var callbackIndex = getReactiveHookCallbackIndex(node.callee, options); + if (callbackIndex === -1) { + // Not a React Hook call that needs deps. + return; + } + var callback = node.arguments[callbackIndex]; + var reactiveHook = node.callee; + var nodeWithoutNamespace = getNodeWithoutReactNamespace(reactiveHook); + var reactiveHookName = 'name' in nodeWithoutNamespace ? nodeWithoutNamespace.name : ''; + var maybeNode = node.arguments[callbackIndex + 1]; + var declaredDependenciesNode = maybeNode && + !(maybeNode.type === 'Identifier' && maybeNode.name === 'undefined') + ? maybeNode + : undefined; + var isEffect = /Effect($|[^a-z])/g.test(reactiveHookName); + // Check whether a callback is supplied. If there is no callback supplied + // then the hook will not work and React will throw a TypeError. + // So no need to check for dependency inclusion. + if (!callback) { + reportProblem({ + node: reactiveHook, + message: "React Hook ".concat(reactiveHookName, " requires an effect callback. ") + + "Did you forget to pass a callback to the hook?", + }); + return; + } + // Check the declared dependencies for this reactive hook. If there is no + // second argument then the reactive callback will re-run on every render. + // So no need to check for dependency inclusion. + if (!declaredDependenciesNode && !isEffect) { + // These are only used for optimization. + if (reactiveHookName === 'useMemo' || + reactiveHookName === 'useCallback') { + // TODO: Can this have a suggestion? + reportProblem({ + node: reactiveHook, + message: "React Hook ".concat(reactiveHookName, " does nothing when called with ") + + "only one argument. Did you forget to pass an array of " + + "dependencies?", + }); + } + return; + } + while (callback.type === 'TSAsExpression' || + callback.type === 'AsExpression') { + callback = callback.expression; + } + switch (callback.type) { + case 'FunctionExpression': + case 'ArrowFunctionExpression': + visitFunctionWithDependencies(callback, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect); + return; // Handled + case 'Identifier': + if (!declaredDependenciesNode) { + // No deps, no problems. + return; // Handled + } + // The function passed as a callback is not written inline. + // But perhaps it's in the dependencies array? + if ('elements' in declaredDependenciesNode && + declaredDependenciesNode.elements && + declaredDependenciesNode.elements.some(function (el) { return el && el.type === 'Identifier' && el.name === callback.name; })) { + // If it's already in the list of deps, we don't care because + // this is valid regardless. + return; // Handled + } + // We'll do our best effort to find it, complain otherwise. + var variable = getScope(callback).set.get(callback.name); + if (variable == null || variable.defs == null) { + // If it's not in scope, we don't care. + return; // Handled + } + // The function passed as a callback is not written inline. + // But it's defined somewhere in the render scope. + // We'll do our best effort to find and check it, complain otherwise. + var def = variable.defs[0]; + if (!def || !def.node) { + break; // Unhandled + } + if (def.type === 'Parameter') { + reportProblem({ + node: reactiveHook, + message: getUnknownDependenciesMessage(reactiveHookName), + }); + return; + } + if (def.type !== 'Variable' && def.type !== 'FunctionName') { + // Parameter or an unusual pattern. Bail out. + break; // Unhandled + } + switch (def.node.type) { + case 'FunctionDeclaration': + // useEffect(() => { ... }, []); + visitFunctionWithDependencies(def.node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect); + return; // Handled + case 'VariableDeclarator': + var init = def.node.init; + if (!init) { + break; // Unhandled + } + switch (init.type) { + // const effectBody = () => {...}; + // useEffect(effectBody, []); + case 'ArrowFunctionExpression': + case 'FunctionExpression': + // We can inspect this function as if it were inline. + visitFunctionWithDependencies(init, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect); + return; // Handled + } + break; // Unhandled + } + break; // Unhandled + default: + // useEffect(generateEffectBody(), []); + reportProblem({ + node: reactiveHook, + message: getUnknownDependenciesMessage(reactiveHookName), + }); + return; // Handled + } + // Something unusual. Fall back to suggesting to add the body itself as a dep. + reportProblem({ + node: reactiveHook, + message: "React Hook ".concat(reactiveHookName, " has a missing dependency: '").concat(callback.name, "'. ") + + "Either include it or remove the dependency array.", + suggest: [ + { + desc: "Update the dependencies array to be: [".concat(callback.name, "]"), + fix: function (fixer) { + return fixer.replaceText(declaredDependenciesNode, "[".concat(callback.name, "]")); + }, + }, + ], + }); + } + return { + CallExpression: visitCallExpression, + }; + }, +}; +// The meat of the logic. +function collectRecommendations(_a) { + var dependencies = _a.dependencies, declaredDependencies = _a.declaredDependencies, stableDependencies = _a.stableDependencies, externalDependencies = _a.externalDependencies, isEffect = _a.isEffect; + // Our primary data structure. + // It is a logical representation of property chains: + // `props` -> `props.foo` -> `props.foo.bar` -> `props.foo.bar.baz` + // -> `props.lol` + // -> `props.huh` -> `props.huh.okay` + // -> `props.wow` + // We'll use it to mark nodes that are *used* by the programmer, + // and the nodes that were *declared* as deps. Then we will + // traverse it to learn which deps are missing or unnecessary. + var depTree = createDepTree(); + function createDepTree() { + return { + isUsed: false, // True if used in code + isSatisfiedRecursively: false, // True if specified in deps + isSubtreeUsed: false, // True if something deeper is used by code + children: new Map(), // Nodes for properties + }; + } + // Mark all required nodes first. + // Imagine exclamation marks next to each used deep property. + dependencies.forEach(function (_, key) { + var node = getOrCreateNodeByPath(depTree, key); + node.isUsed = true; + markAllParentsByPath(depTree, key, function (parent) { + parent.isSubtreeUsed = true; + }); + }); + // Mark all satisfied nodes. + // Imagine checkmarks next to each declared dependency. + declaredDependencies.forEach(function (_a) { + var key = _a.key; + var node = getOrCreateNodeByPath(depTree, key); + node.isSatisfiedRecursively = true; + }); + stableDependencies.forEach(function (key) { + var node = getOrCreateNodeByPath(depTree, key); + node.isSatisfiedRecursively = true; + }); + // Tree manipulation helpers. + function getOrCreateNodeByPath(rootNode, path) { + var e_13, _a; + var keys = path.split('.'); + var node = rootNode; + try { + for (var keys_1 = __values(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) { + var key = keys_1_1.value; + var child = node.children.get(key); + if (!child) { + child = createDepTree(); + node.children.set(key, child); + } + node = child; + } + } + catch (e_13_1) { e_13 = { error: e_13_1 }; } + finally { + try { + if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return)) _a.call(keys_1); + } + finally { if (e_13) throw e_13.error; } + } + return node; + } + function markAllParentsByPath(rootNode, path, fn) { + var e_14, _a; + var keys = path.split('.'); + var node = rootNode; + try { + for (var keys_2 = __values(keys), keys_2_1 = keys_2.next(); !keys_2_1.done; keys_2_1 = keys_2.next()) { + var key = keys_2_1.value; + var child = node.children.get(key); + if (!child) { + return; + } + fn(child); + node = child; + } + } + catch (e_14_1) { e_14 = { error: e_14_1 }; } + finally { + try { + if (keys_2_1 && !keys_2_1.done && (_a = keys_2.return)) _a.call(keys_2); + } + finally { if (e_14) throw e_14.error; } + } + } + // Now we can learn which dependencies are missing or necessary. + var missingDependencies = new Set(); + var satisfyingDependencies = new Set(); + scanTreeRecursively(depTree, missingDependencies, satisfyingDependencies, function (key) { return key; }); + function scanTreeRecursively(node, missingPaths, satisfyingPaths, keyToPath) { + node.children.forEach(function (child, key) { + var path = keyToPath(key); + if (child.isSatisfiedRecursively) { + if (child.isSubtreeUsed) { + // Remember this dep actually satisfied something. + satisfyingPaths.add(path); + } + // It doesn't matter if there's something deeper. + // It would be transitively satisfied since we assume immutability. + // `props.foo` is enough if you read `props.foo.id`. + return; + } + if (child.isUsed) { + // Remember that no declared deps satisfied this node. + missingPaths.add(path); + // If we got here, nothing in its subtree was satisfied. + // No need to search further. + return; + } + scanTreeRecursively(child, missingPaths, satisfyingPaths, function (childKey) { return path + '.' + childKey; }); + }); + } + // Collect suggestions in the order they were originally specified. + var suggestedDependencies = []; + var unnecessaryDependencies = new Set(); + var duplicateDependencies = new Set(); + declaredDependencies.forEach(function (_a) { + var key = _a.key; + // Does this declared dep satisfy a real need? + if (satisfyingDependencies.has(key)) { + if (suggestedDependencies.indexOf(key) === -1) { + // Good one. + suggestedDependencies.push(key); + } + else { + // Duplicate. + duplicateDependencies.add(key); + } + } + else { + if (isEffect && + !key.endsWith('.current') && + !externalDependencies.has(key)) { + // Effects are allowed extra "unnecessary" deps. + // Such as resetting scroll when ID changes. + // Consider them legit. + // The exception is ref.current which is always wrong. + if (suggestedDependencies.indexOf(key) === -1) { + suggestedDependencies.push(key); + } + } + else { + // It's definitely not needed. + unnecessaryDependencies.add(key); + } + } + }); + // Then add the missing ones at the end. + missingDependencies.forEach(function (key) { + suggestedDependencies.push(key); + }); + return { + suggestedDependencies: suggestedDependencies, + unnecessaryDependencies: unnecessaryDependencies, + duplicateDependencies: duplicateDependencies, + missingDependencies: missingDependencies, + }; +} +// If the node will result in constructing a referentially unique value, return +// its human readable type name, else return null. +function getConstructionExpressionType(node) { + switch (node.type) { + case 'ObjectExpression': + return 'object'; + case 'ArrayExpression': + return 'array'; + case 'ArrowFunctionExpression': + case 'FunctionExpression': + return 'function'; + case 'ClassExpression': + return 'class'; + case 'ConditionalExpression': + if (getConstructionExpressionType(node.consequent) != null || + getConstructionExpressionType(node.alternate) != null) { + return 'conditional'; + } + return null; + case 'LogicalExpression': + if (getConstructionExpressionType(node.left) != null || + getConstructionExpressionType(node.right) != null) { + return 'logical expression'; + } + return null; + case 'JSXFragment': + return 'JSX fragment'; + case 'JSXElement': + return 'JSX element'; + case 'AssignmentExpression': + if (getConstructionExpressionType(node.right) != null) { + return 'assignment expression'; + } + return null; + case 'NewExpression': + return 'object construction'; + case 'Literal': + if (node.value instanceof RegExp) { + return 'regular expression'; + } + return null; + case 'TypeCastExpression': + case 'AsExpression': + case 'TSAsExpression': + return getConstructionExpressionType(node.expression); + } + return null; +} +// Finds variables declared as dependencies +// that would invalidate on every render. +function scanForConstructions(_a) { + var declaredDependencies = _a.declaredDependencies, declaredDependenciesNode = _a.declaredDependenciesNode, componentScope = _a.componentScope, scope = _a.scope; + var constructions = declaredDependencies + .map(function (_a) { + var key = _a.key; + var ref = componentScope.variables.find(function (v) { return v.name === key; }); + if (ref == null) { + return null; + } + var node = ref.defs[0]; + if (node == null) { + return null; + } + // const handleChange = function () {} + // const handleChange = () => {} + // const foo = {} + // const foo = [] + // etc. + if (node.type === 'Variable' && + node.node.type === 'VariableDeclarator' && + node.node.id.type === 'Identifier' && // Ensure this is not destructed assignment + node.node.init != null) { + var constantExpressionType = getConstructionExpressionType(node.node.init); + if (constantExpressionType) { + return [ref, constantExpressionType]; + } + } + // function handleChange() {} + if (node.type === 'FunctionName' && + node.node.type === 'FunctionDeclaration') { + return [ref, 'function']; + } + // class Foo {} + if (node.type === 'ClassName' && node.node.type === 'ClassDeclaration') { + return [ref, 'class']; + } + return null; + }) + .filter(Boolean); + function isUsedOutsideOfHook(ref) { + var e_15, _a; + var foundWriteExpr = false; + try { + for (var _b = __values(ref.references), _c = _b.next(); !_c.done; _c = _b.next()) { + var reference = _c.value; + if (reference.writeExpr) { + if (foundWriteExpr) { + // Two writes to the same function. + return true; + } + else { + // Ignore first write as it's not usage. + foundWriteExpr = true; + continue; + } + } + var currentScope = reference.from; + while (currentScope !== scope && currentScope != null) { + currentScope = currentScope.upper; + } + if (currentScope !== scope) { + // This reference is outside the Hook callback. + // It can only be legit if it's the deps array. + if (!isAncestorNodeOf(declaredDependenciesNode, reference.identifier)) { + return true; + } + } + } + } + catch (e_15_1) { e_15 = { error: e_15_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + } + finally { if (e_15) throw e_15.error; } + } + return false; + } + return constructions.map(function (_a) { + var _b = __read(_a, 2), ref = _b[0], depType = _b[1]; + return ({ + construction: ref.defs[0], + depType: depType, + isUsedOutsideOfHook: isUsedOutsideOfHook(ref), + }); + }); +} +/** + * Assuming () means the passed/returned node: + * (props) => (props) + * props.(foo) => (props.foo) + * props.foo.(bar) => (props).foo.bar + * props.foo.bar.(baz) => (props).foo.bar.baz + */ +function getDependency(node) { + if (node.parent && + (node.parent.type === 'MemberExpression' || + node.parent.type === 'OptionalMemberExpression') && + node.parent.object === node && + 'name' in node.parent.property && + node.parent.property.name !== 'current' && + !node.parent.computed && + !(node.parent.parent != null && + (node.parent.parent.type === 'CallExpression' || + node.parent.parent.type === 'OptionalCallExpression') && + node.parent.parent.callee === node.parent)) { + return getDependency(node.parent); + } + else if ( + // Note: we don't check OptionalMemberExpression because it can't be LHS. + node.type === 'MemberExpression' && + node.parent && + node.parent.type === 'AssignmentExpression' && + node.parent.left === node) { + return node.object; + } + else { + return node; + } +} +/** + * Mark a node as either optional or required. + * Note: If the node argument is an OptionalMemberExpression, it doesn't necessarily mean it is optional. + * It just means there is an optional member somewhere inside. + * This particular node might still represent a required member, so check .optional field. + */ +function markNode(node, optionalChains, result) { + if (optionalChains) { + if ('optional' in node && node.optional) { + // We only want to consider it optional if *all* usages were optional. + if (!optionalChains.has(result)) { + // Mark as (maybe) optional. If there's a required usage, this will be overridden. + optionalChains.set(result, true); + } + } + else { + // Mark as required. + optionalChains.set(result, false); + } + } +} +/** + * Assuming () means the passed node. + * (foo) -> 'foo' + * foo(.)bar -> 'foo.bar' + * foo.bar(.)baz -> 'foo.bar.baz' + * Otherwise throw. + */ +function analyzePropertyChain(node, optionalChains) { + if (node.type === 'Identifier' || node.type === 'JSXIdentifier') { + var result = node.name; + if (optionalChains) { + // Mark as required. + optionalChains.set(result, false); + } + return result; + } + else if (node.type === 'MemberExpression' && !node.computed) { + var object = analyzePropertyChain(node.object, optionalChains); + var property = analyzePropertyChain(node.property, null); + var result = "".concat(object, ".").concat(property); + markNode(node, optionalChains, result); + return result; + } + else if (node.type === 'OptionalMemberExpression' && !node.computed) { + var object = analyzePropertyChain(node.object, optionalChains); + var property = analyzePropertyChain(node.property, null); + var result = "".concat(object, ".").concat(property); + markNode(node, optionalChains, result); + return result; + } + else if (node.type === 'ChainExpression' && + (!('computed' in node) || !node.computed)) { + var expression = node.expression; + if (expression.type === 'CallExpression') { + throw new Error("Unsupported node type: ".concat(expression.type)); + } + var object = analyzePropertyChain(expression.object, optionalChains); + var property = analyzePropertyChain(expression.property, null); + var result = "".concat(object, ".").concat(property); + markNode(expression, optionalChains, result); + return result; + } + else { + throw new Error("Unsupported node type: ".concat(node.type)); + } +} +function getNodeWithoutReactNamespace(node) { + if (node.type === 'MemberExpression' && + node.object.type === 'Identifier' && + node.object.name === 'React' && + node.property.type === 'Identifier' && + !node.computed) { + return node.property; + } + return node; +} +// What's the index of callback that needs to be analyzed for a given Hook? +// -1 if it's not a Hook we care about (e.g. useState). +// 0 for useEffect/useMemo/useCallback(fn). +// 1 for useImperativeHandle(ref, fn). +// For additionally configured Hooks, assume that they're like useEffect (0). +function getReactiveHookCallbackIndex(calleeNode, options) { + var node = getNodeWithoutReactNamespace(calleeNode); + if (node.type !== 'Identifier') { + return -1; + } + switch (node.name) { + case 'useEffect': + case 'useLayoutEffect': + case 'useCallback': + case 'useMemo': + // useEffect(fn) + return 0; + case 'useImperativeHandle': + // useImperativeHandle(ref, fn) + return 1; + default: + if (node === calleeNode && options && options.additionalHooks) { + // Allow the user to provide a regular expression which enables the lint to + // target custom reactive hooks. + var name = void 0; + try { + name = analyzePropertyChain(node, null); + } + catch (error) { + if (error instanceof Error && + /Unsupported node type/.test(error.message)) { + return 0; + } + else { + throw error; + } + } + return options.additionalHooks.test(name) ? 0 : -1; + } + else { + return -1; + } + } +} +/** + * ESLint won't assign node.parent to references from context.getScope() + * + * So instead we search for the node from an ancestor assigning node.parent + * as we go. This mutates the AST. + * + * This traversal is: + * - optimized by only searching nodes with a range surrounding our target node + * - agnostic to AST node types, it looks for `{ type: string, ... }` + */ +function fastFindReferenceWithParent(start, target) { + var e_16, _a; + var queue = [start]; + var item; + while (queue.length) { + item = queue.shift(); + if (isSameIdentifier(item, target)) { + return item; + } + if (!isAncestorNodeOf(item, target)) { + continue; + } + try { + for (var _b = (e_16 = void 0, __values(Object.entries(item))), _c = _b.next(); !_c.done; _c = _b.next()) { + var _d = __read(_c.value, 2), key = _d[0], value = _d[1]; + if (key === 'parent') { + continue; + } + if (isNodeLike(value)) { + value.parent = item; + queue.push(value); + } + else if (Array.isArray(value)) { + value.forEach(function (val) { + if (isNodeLike(val)) { + val.parent = item; + queue.push(val); + } + }); + } + } + } + catch (e_16_1) { e_16 = { error: e_16_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + } + finally { if (e_16) throw e_16.error; } + } + } + return null; +} +function joinEnglish(arr) { + var s = ''; + for (var i = 0; i < arr.length; i++) { + s += arr[i]; + if (i === 0 && arr.length === 2) { + s += ' and '; + } + else if (i === arr.length - 2 && arr.length > 2) { + s += ', and '; + } + else if (i < arr.length - 1) { + s += ', '; + } + } + return s; +} +function isNodeLike(val) { + return (typeof val === 'object' && + val !== null && + !Array.isArray(val) && + 'type' in val && + typeof val.type === 'string'); +} +function isSameIdentifier(a, b) { + return ((a.type === 'Identifier' || a.type === 'JSXIdentifier') && + a.type === b.type && + a.name === b.name && + !!a.range && + !!b.range && + a.range[0] === b.range[0] && + a.range[1] === b.range[1]); +} +function isAncestorNodeOf(a, b) { + return (!!a.range && + !!b.range && + a.range[0] <= b.range[0] && + a.range[1] >= b.range[1]); +} +function isUseEffectEventIdentifier(node) { + return false; +} +function getUnknownDependenciesMessage(reactiveHookName) { + return ("React Hook ".concat(reactiveHookName, " received a function whose dependencies ") + + "are unknown. Pass an inline function instead."); +} + +// All rules +var rules = { + 'rules-of-hooks': rule$1, + 'exhaustive-deps': rule, +}; +// Config rules +var configRules = { + 'react-hooks/rules-of-hooks': 'error', + 'react-hooks/exhaustive-deps': 'warn', +}; +// Legacy config +var legacyRecommendedConfig = { + plugins: ['react-hooks'], + rules: configRules, +}; +// Plugin object +var plugin = { + // TODO: Make this more dynamic to populate version from package.json. + // This can be done by injecting at build time, since importing the package.json isn't an option in Meta + meta: { name: 'eslint-plugin-react-hooks' }, + rules: rules, + configs: { + /** Legacy recommended config, to be used with rc-based configurations */ + 'recommended-legacy': legacyRecommendedConfig, + /** + * 'recommended' is currently aliased to the legacy / rc recommended config) to maintain backwards compatibility. + * This is deprecated and in v6, it will switch to alias the flat recommended config. + */ + recommended: legacyRecommendedConfig, + /** Latest recommended config, to be used with flat configurations */ + 'recommended-latest': { + name: 'react-hooks/recommended', + plugins: { + get 'react-hooks'() { + return plugin; + }, + }, + rules: configRules, + }, + }, +}; +var configs = plugin.configs; +var meta = plugin.meta; +// TODO: If the plugin is ever updated to be pure ESM and drops support for rc-based configs, then it should be exporting the plugin as default +// instead of individual named exports. +// export default plugin; + +exports.configs = configs; +exports.meta = meta; +exports.rules = rules; + })(); +} diff --git a/node_modules/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.production.js b/node_modules/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.production.js new file mode 100644 index 0000000000000000000000000000000000000000..f646fa15bda010d40af42d246e6be4c8e1bb4a64 --- /dev/null +++ b/node_modules/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.production.js @@ -0,0 +1,2731 @@ +/** + * @license React + * eslint-plugin-react-hooks.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +'use strict'; + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise */ + + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +} + +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || from); +} + +/* eslint-disable no-for-of-loops/no-for-of-loops */ +/** + * Catch all identifiers that begin with "use" followed by an uppercase Latin + * character to exclude identifiers like "user". + */ +function isHookName(s) { + return s === 'use' || /^use[A-Z0-9]/.test(s); +} +/** + * We consider hooks to be a hook name identifier or a member expression + * containing a hook name. + */ +function isHook(node) { + if (node.type === 'Identifier') { + return isHookName(node.name); + } + else if (node.type === 'MemberExpression' && + !node.computed && + isHook(node.property)) { + var obj = node.object; + var isPascalCaseNameSpace = /^[A-Z].*/; + return obj.type === 'Identifier' && isPascalCaseNameSpace.test(obj.name); + } + else { + return false; + } +} +/** + * Checks if the node is a React component name. React component names must + * always start with an uppercase letter. + */ +function isComponentName(node) { + return node.type === 'Identifier' && /^[A-Z]/.test(node.name); +} +function isReactFunction(node, functionName) { + return (('name' in node && node.name === functionName) || + (node.type === 'MemberExpression' && + 'name' in node.object && + node.object.name === 'React' && + 'name' in node.property && + node.property.name === functionName)); +} +/** + * Checks if the node is a callback argument of forwardRef. This render function + * should follow the rules of hooks. + */ +function isForwardRefCallback(node) { + return !!(node.parent && + 'callee' in node.parent && + node.parent.callee && + isReactFunction(node.parent.callee, 'forwardRef')); +} +/** + * Checks if the node is a callback argument of React.memo. This anonymous + * functional component should follow the rules of hooks. + */ +function isMemoCallback(node) { + return !!(node.parent && + 'callee' in node.parent && + node.parent.callee && + isReactFunction(node.parent.callee, 'memo')); +} +function isInsideComponentOrHook(node) { + while (node) { + var functionName = getFunctionName(node); + if (functionName) { + if (isComponentName(functionName) || isHook(functionName)) { + return true; + } + } + if (isForwardRefCallback(node) || isMemoCallback(node)) { + return true; + } + node = node.parent; + } + return false; +} +function isInsideDoWhileLoop(node) { + while (node) { + if (node.type === 'DoWhileStatement') { + return true; + } + node = node.parent; + } + return false; +} +function isUseEffectEventIdentifier$1(node) { + return false; +} +function isUseIdentifier(node) { + return isReactFunction(node, 'use'); +} +var rule$1 = { + meta: { + type: 'problem', + docs: { + description: 'enforces the Rules of Hooks', + recommended: true, + url: 'https://reactjs.org/docs/hooks-rules.html', + }, + }, + create: function (context) { + var lastEffect = null; + var codePathReactHooksMapStack = []; + var codePathSegmentStack = []; + var useEffectEventFunctions = new WeakSet(); + // For a given scope, iterate through the references and add all useEffectEvent definitions. We can + // do this in non-Program nodes because we can rely on the assumption that useEffectEvent functions + // can only be declared within a component or hook at its top level. + function recordAllUseEffectEventFunctions(scope) { + var e_1, _a, e_2, _b; + try { + for (var _c = __values(scope.references), _d = _c.next(); !_d.done; _d = _c.next()) { + var reference = _d.value; + var parent = reference.identifier.parent; + if ((parent === null || parent === void 0 ? void 0 : parent.type) === 'VariableDeclarator' && + parent.init && + parent.init.type === 'CallExpression' && + parent.init.callee && + isUseEffectEventIdentifier$1(parent.init.callee)) { + if (reference.resolved === null) { + throw new Error('Unexpected null reference.resolved'); + } + try { + for (var _e = (e_2 = void 0, __values(reference.resolved.references)), _f = _e.next(); !_f.done; _f = _e.next()) { + var ref = _f.value; + if (ref !== reference) { + useEffectEventFunctions.add(ref.identifier); + } + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_f && !_f.done && (_b = _e.return)) _b.call(_e); + } + finally { if (e_2) throw e_2.error; } + } + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_d && !_d.done && (_a = _c.return)) _a.call(_c); + } + finally { if (e_1) throw e_1.error; } + } + } + /** + * SourceCode that also works down to ESLint 3.0.0 + */ + var getSourceCode = typeof context.getSourceCode === 'function' + ? function () { + return context.getSourceCode(); + } + : function () { + return context.sourceCode; + }; + /** + * SourceCode#getScope that also works down to ESLint 3.0.0 + */ + var getScope = typeof context.getScope === 'function' + ? function () { + return context.getScope(); + } + : function (node) { + return getSourceCode().getScope(node); + }; + return { + // Maintain code segment path stack as we traverse. + onCodePathSegmentStart: function (segment) { return codePathSegmentStack.push(segment); }, + onCodePathSegmentEnd: function () { return codePathSegmentStack.pop(); }, + // Maintain code path stack as we traverse. + onCodePathStart: function () { + return codePathReactHooksMapStack.push(new Map()); + }, + // Process our code path. + // + // Everything is ok if all React Hooks are both reachable from the initial + // segment and reachable from every final segment. + onCodePathEnd: function (codePath, codePathNode) { + var e_3, _a, e_4, _b, e_5, _c; + var reactHooksMap = codePathReactHooksMapStack.pop(); + if ((reactHooksMap === null || reactHooksMap === void 0 ? void 0 : reactHooksMap.size) === 0) { + return; + } + else if (typeof reactHooksMap === 'undefined') { + throw new Error('Unexpected undefined reactHooksMap'); + } + // All of the segments which are cyclic are recorded in this set. + var cyclic = new Set(); + /** + * Count the number of code paths from the start of the function to this + * segment. For example: + * + * ```js + * function MyComponent() { + * if (condition) { + * // Segment 1 + * } else { + * // Segment 2 + * } + * // Segment 3 + * } + * ``` + * + * Segments 1 and 2 have one path to the beginning of `MyComponent` and + * segment 3 has two paths to the beginning of `MyComponent` since we + * could have either taken the path of segment 1 or segment 2. + * + * Populates `cyclic` with cyclic segments. + */ + function countPathsFromStart(segment, pathHistory) { + var e_6, _a, e_7, _b; + var cache = countPathsFromStart.cache; + var paths = cache.get(segment.id); + var pathList = new Set(pathHistory); + // If `pathList` includes the current segment then we've found a cycle! + // We need to fill `cyclic` with all segments inside cycle + if (pathList.has(segment.id)) { + var pathArray = __spreadArray([], __read(pathList), false); + var cyclicSegments = pathArray.slice(pathArray.indexOf(segment.id) + 1); + try { + for (var cyclicSegments_1 = __values(cyclicSegments), cyclicSegments_1_1 = cyclicSegments_1.next(); !cyclicSegments_1_1.done; cyclicSegments_1_1 = cyclicSegments_1.next()) { + var cyclicSegment = cyclicSegments_1_1.value; + cyclic.add(cyclicSegment); + } + } + catch (e_6_1) { e_6 = { error: e_6_1 }; } + finally { + try { + if (cyclicSegments_1_1 && !cyclicSegments_1_1.done && (_a = cyclicSegments_1.return)) _a.call(cyclicSegments_1); + } + finally { if (e_6) throw e_6.error; } + } + return BigInt('0'); + } + // add the current segment to pathList + pathList.add(segment.id); + // We have a cached `paths`. Return it. + if (paths !== undefined) { + return paths; + } + if (codePath.thrownSegments.includes(segment)) { + paths = BigInt('0'); + } + else if (segment.prevSegments.length === 0) { + paths = BigInt('1'); + } + else { + paths = BigInt('0'); + try { + for (var _c = __values(segment.prevSegments), _d = _c.next(); !_d.done; _d = _c.next()) { + var prevSegment = _d.value; + paths += countPathsFromStart(prevSegment, pathList); + } + } + catch (e_7_1) { e_7 = { error: e_7_1 }; } + finally { + try { + if (_d && !_d.done && (_b = _c.return)) _b.call(_c); + } + finally { if (e_7) throw e_7.error; } + } + } + // If our segment is reachable then there should be at least one path + // to it from the start of our code path. + if (segment.reachable && paths === BigInt('0')) { + cache.delete(segment.id); + } + else { + cache.set(segment.id, paths); + } + return paths; + } + /** + * Count the number of code paths from this segment to the end of the + * function. For example: + * + * ```js + * function MyComponent() { + * // Segment 1 + * if (condition) { + * // Segment 2 + * } else { + * // Segment 3 + * } + * } + * ``` + * + * Segments 2 and 3 have one path to the end of `MyComponent` and + * segment 1 has two paths to the end of `MyComponent` since we could + * either take the path of segment 1 or segment 2. + * + * Populates `cyclic` with cyclic segments. + */ + function countPathsToEnd(segment, pathHistory) { + var e_8, _a, e_9, _b; + var cache = countPathsToEnd.cache; + var paths = cache.get(segment.id); + var pathList = new Set(pathHistory); + // If `pathList` includes the current segment then we've found a cycle! + // We need to fill `cyclic` with all segments inside cycle + if (pathList.has(segment.id)) { + var pathArray = Array.from(pathList); + var cyclicSegments = pathArray.slice(pathArray.indexOf(segment.id) + 1); + try { + for (var cyclicSegments_2 = __values(cyclicSegments), cyclicSegments_2_1 = cyclicSegments_2.next(); !cyclicSegments_2_1.done; cyclicSegments_2_1 = cyclicSegments_2.next()) { + var cyclicSegment = cyclicSegments_2_1.value; + cyclic.add(cyclicSegment); + } + } + catch (e_8_1) { e_8 = { error: e_8_1 }; } + finally { + try { + if (cyclicSegments_2_1 && !cyclicSegments_2_1.done && (_a = cyclicSegments_2.return)) _a.call(cyclicSegments_2); + } + finally { if (e_8) throw e_8.error; } + } + return BigInt('0'); + } + // add the current segment to pathList + pathList.add(segment.id); + // We have a cached `paths`. Return it. + if (paths !== undefined) { + return paths; + } + if (codePath.thrownSegments.includes(segment)) { + paths = BigInt('0'); + } + else if (segment.nextSegments.length === 0) { + paths = BigInt('1'); + } + else { + paths = BigInt('0'); + try { + for (var _c = __values(segment.nextSegments), _d = _c.next(); !_d.done; _d = _c.next()) { + var nextSegment = _d.value; + paths += countPathsToEnd(nextSegment, pathList); + } + } + catch (e_9_1) { e_9 = { error: e_9_1 }; } + finally { + try { + if (_d && !_d.done && (_b = _c.return)) _b.call(_c); + } + finally { if (e_9) throw e_9.error; } + } + } + cache.set(segment.id, paths); + return paths; + } + /** + * Gets the shortest path length to the start of a code path. + * For example: + * + * ```js + * function MyComponent() { + * if (condition) { + * // Segment 1 + * } + * // Segment 2 + * } + * ``` + * + * There is only one path from segment 1 to the code path start. Its + * length is one so that is the shortest path. + * + * There are two paths from segment 2 to the code path start. One + * through segment 1 with a length of two and another directly to the + * start with a length of one. The shortest path has a length of one + * so we would return that. + */ + function shortestPathLengthToStart(segment) { + var e_10, _a; + var cache = shortestPathLengthToStart.cache; + var length = cache.get(segment.id); + // If `length` is null then we found a cycle! Return infinity since + // the shortest path is definitely not the one where we looped. + if (length === null) { + return Infinity; + } + // We have a cached `length`. Return it. + if (length !== undefined) { + return length; + } + // Compute `length` and cache it. Guarding against cycles. + cache.set(segment.id, null); + if (segment.prevSegments.length === 0) { + length = 1; + } + else { + length = Infinity; + try { + for (var _b = __values(segment.prevSegments), _c = _b.next(); !_c.done; _c = _b.next()) { + var prevSegment = _c.value; + var prevLength = shortestPathLengthToStart(prevSegment); + if (prevLength < length) { + length = prevLength; + } + } + } + catch (e_10_1) { e_10 = { error: e_10_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + } + finally { if (e_10) throw e_10.error; } + } + length += 1; + } + cache.set(segment.id, length); + return length; + } + countPathsFromStart.cache = new Map(); + countPathsToEnd.cache = new Map(); + shortestPathLengthToStart.cache = new Map(); + // Count all code paths to the end of our component/hook. Also primes + // the `countPathsToEnd` cache. + var allPathsFromStartToEnd = countPathsToEnd(codePath.initialSegment); + // Gets the function name for our code path. If the function name is + // `undefined` then we know either that we have an anonymous function + // expression or our code path is not in a function. In both cases we + // will want to error since neither are React function components or + // hook functions - unless it is an anonymous function argument to + // forwardRef or memo. + var codePathFunctionName = getFunctionName(codePathNode); + // This is a valid code path for React hooks if we are directly in a React + // function component or we are in a hook function. + var isSomewhereInsideComponentOrHook = isInsideComponentOrHook(codePathNode); + var isDirectlyInsideComponentOrHook = codePathFunctionName + ? isComponentName(codePathFunctionName) || + isHook(codePathFunctionName) + : isForwardRefCallback(codePathNode) || isMemoCallback(codePathNode); + // Compute the earliest finalizer level using information from the + // cache. We expect all reachable final segments to have a cache entry + // after calling `visitSegment()`. + var shortestFinalPathLength = Infinity; + try { + for (var _d = __values(codePath.finalSegments), _e = _d.next(); !_e.done; _e = _d.next()) { + var finalSegment = _e.value; + if (!finalSegment.reachable) { + continue; + } + var length = shortestPathLengthToStart(finalSegment); + if (length < shortestFinalPathLength) { + shortestFinalPathLength = length; + } + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (_e && !_e.done && (_a = _d.return)) _a.call(_d); + } + finally { if (e_3) throw e_3.error; } + } + try { + // Make sure all React Hooks pass our lint invariants. Log warnings + // if not. + for (var reactHooksMap_1 = __values(reactHooksMap), reactHooksMap_1_1 = reactHooksMap_1.next(); !reactHooksMap_1_1.done; reactHooksMap_1_1 = reactHooksMap_1.next()) { + var _f = __read(reactHooksMap_1_1.value, 2), segment = _f[0], reactHooks = _f[1]; + // NOTE: We could report here that the hook is not reachable, but + // that would be redundant with more general "no unreachable" + // lint rules. + if (!segment.reachable) { + continue; + } + // If there are any final segments with a shorter path to start then + // we possibly have an early return. + // + // If our segment is a final segment itself then siblings could + // possibly be early returns. + var possiblyHasEarlyReturn = segment.nextSegments.length === 0 + ? shortestFinalPathLength <= shortestPathLengthToStart(segment) + : shortestFinalPathLength < shortestPathLengthToStart(segment); + // Count all the paths from the start of our code path to the end of + // our code path that go _through_ this segment. The critical piece + // of this is _through_. If we just call `countPathsToEnd(segment)` + // then we neglect that we may have gone through multiple paths to get + // to this point! Consider: + // + // ```js + // function MyComponent() { + // if (a) { + // // Segment 1 + // } else { + // // Segment 2 + // } + // // Segment 3 + // if (b) { + // // Segment 4 + // } else { + // // Segment 5 + // } + // } + // ``` + // + // In this component we have four code paths: + // + // 1. `a = true; b = true` + // 2. `a = true; b = false` + // 3. `a = false; b = true` + // 4. `a = false; b = false` + // + // From segment 3 there are two code paths to the end through segment + // 4 and segment 5. However, we took two paths to get here through + // segment 1 and segment 2. + // + // If we multiply the paths from start (two) by the paths to end (two) + // for segment 3 we get four. Which is our desired count. + var pathsFromStartToEnd = countPathsFromStart(segment) * countPathsToEnd(segment); + // Is this hook a part of a cyclic segment? + var cycled = cyclic.has(segment.id); + try { + for (var reactHooks_1 = (e_5 = void 0, __values(reactHooks)), reactHooks_1_1 = reactHooks_1.next(); !reactHooks_1_1.done; reactHooks_1_1 = reactHooks_1.next()) { + var hook = reactHooks_1_1.value; + // Report an error if a hook may be called more then once. + // `use(...)` can be called in loops. + if ((cycled || isInsideDoWhileLoop(hook)) && + !isUseIdentifier(hook)) { + context.report({ + node: hook, + message: "React Hook \"".concat(getSourceCode().getText(hook), "\" may be executed ") + + 'more than once. Possibly because it is called in a loop. ' + + 'React Hooks must be called in the exact same order in ' + + 'every component render.', + }); + } + // If this is not a valid code path for React hooks then we need to + // log a warning for every hook in this code path. + // + // Pick a special message depending on the scope this hook was + // called in. + if (isDirectlyInsideComponentOrHook) { + // Report an error if the hook is called inside an async function. + // @ts-expect-error the above check hasn't properly type-narrowed `codePathNode` (async doesn't exist on Node) + var isAsyncFunction = codePathNode.async; + if (isAsyncFunction) { + context.report({ + node: hook, + message: "React Hook \"".concat(getSourceCode().getText(hook), "\" cannot be ") + + 'called in an async function.', + }); + } + // Report an error if a hook does not reach all finalizing code + // path segments. + // + // Special case when we think there might be an early return. + if (!cycled && + pathsFromStartToEnd !== allPathsFromStartToEnd && + !isUseIdentifier(hook) && // `use(...)` can be called conditionally. + !isInsideDoWhileLoop(hook) // wrapping do/while loops are checked separately. + ) { + var message = "React Hook \"".concat(getSourceCode().getText(hook), "\" is called ") + + 'conditionally. React Hooks must be called in the exact ' + + 'same order in every component render.' + + (possiblyHasEarlyReturn + ? ' Did you accidentally call a React Hook after an' + + ' early return?' + : ''); + context.report({ node: hook, message: message }); + } + } + else if (codePathNode.parent != null && + (codePathNode.parent.type === 'MethodDefinition' || + // @ts-expect-error `ClassProperty` was removed from typescript-estree in https://github.com/typescript-eslint/typescript-eslint/pull/3806 + codePathNode.parent.type === 'ClassProperty' || + codePathNode.parent.type === 'PropertyDefinition') && + codePathNode.parent.value === codePathNode) { + // Custom message for hooks inside a class + var message = "React Hook \"".concat(getSourceCode().getText(hook), "\" cannot be called ") + + 'in a class component. React Hooks must be called in a ' + + 'React function component or a custom React Hook function.'; + context.report({ node: hook, message: message }); + } + else if (codePathFunctionName) { + // Custom message if we found an invalid function name. + var message = "React Hook \"".concat(getSourceCode().getText(hook), "\" is called in ") + + "function \"".concat(getSourceCode().getText(codePathFunctionName), "\" ") + + 'that is neither a React function component nor a custom ' + + 'React Hook function.' + + ' React component names must start with an uppercase letter.' + + ' React Hook names must start with the word "use".'; + context.report({ node: hook, message: message }); + } + else if (codePathNode.type === 'Program') { + // These are dangerous if you have inline requires enabled. + var message = "React Hook \"".concat(getSourceCode().getText(hook), "\" cannot be called ") + + 'at the top level. React Hooks must be called in a ' + + 'React function component or a custom React Hook function.'; + context.report({ node: hook, message: message }); + } + else { + // Assume in all other cases the user called a hook in some + // random function callback. This should usually be true for + // anonymous function expressions. Hopefully this is clarifying + // enough in the common case that the incorrect message in + // uncommon cases doesn't matter. + // `use(...)` can be called in callbacks. + if (isSomewhereInsideComponentOrHook && !isUseIdentifier(hook)) { + var message = "React Hook \"".concat(getSourceCode().getText(hook), "\" cannot be called ") + + 'inside a callback. React Hooks must be called in a ' + + 'React function component or a custom React Hook function.'; + context.report({ node: hook, message: message }); + } + } + } + } + catch (e_5_1) { e_5 = { error: e_5_1 }; } + finally { + try { + if (reactHooks_1_1 && !reactHooks_1_1.done && (_c = reactHooks_1.return)) _c.call(reactHooks_1); + } + finally { if (e_5) throw e_5.error; } + } + } + } + catch (e_4_1) { e_4 = { error: e_4_1 }; } + finally { + try { + if (reactHooksMap_1_1 && !reactHooksMap_1_1.done && (_b = reactHooksMap_1.return)) _b.call(reactHooksMap_1); + } + finally { if (e_4) throw e_4.error; } + } + }, + // Missed opportunity...We could visit all `Identifier`s instead of all + // `CallExpression`s and check that _every use_ of a hook name is valid. + // But that gets complicated and enters type-system territory, so we're + // only being strict about hook calls for now. + CallExpression: function (node) { + if (isHook(node.callee)) { + // Add the hook node to a map keyed by the code path segment. We will + // do full code path analysis at the end of our code path. + var reactHooksMap = last(codePathReactHooksMapStack); + var codePathSegment = last(codePathSegmentStack); + var reactHooks = reactHooksMap.get(codePathSegment); + if (!reactHooks) { + reactHooks = []; + reactHooksMap.set(codePathSegment, reactHooks); + } + reactHooks.push(node.callee); + } + // useEffectEvent: useEffectEvent functions can be passed by reference within useEffect as well as in + // another useEffectEvent + if (node.callee.type === 'Identifier' && + (node.callee.name === 'useEffect' || + isUseEffectEventIdentifier$1()) && + node.arguments.length > 0) { + // Denote that we have traversed into a useEffect call, and stash the CallExpr for + // comparison later when we exit + lastEffect = node; + } + }, + Identifier: function (node) { + // This identifier resolves to a useEffectEvent function, but isn't being referenced in an + // effect or another event function. It isn't being called either. + if (lastEffect == null && + useEffectEventFunctions.has(node) && + node.parent.type !== 'CallExpression') { + context.report({ + node: node, + message: "`".concat(getSourceCode().getText(node), "` is a function created with React Hook \"useEffectEvent\", and can only be called from ") + + 'the same component. They cannot be assigned to variables or passed down.', + }); + } + }, + 'CallExpression:exit': function (node) { + if (node === lastEffect) { + lastEffect = null; + } + }, + FunctionDeclaration: function (node) { + // function MyComponent() { const onClick = useEffectEvent(...) } + if (isInsideComponentOrHook(node)) { + recordAllUseEffectEventFunctions(getScope(node)); + } + }, + ArrowFunctionExpression: function (node) { + // const MyComponent = () => { const onClick = useEffectEvent(...) } + if (isInsideComponentOrHook(node)) { + recordAllUseEffectEventFunctions(getScope(node)); + } + }, + }; + }, +}; +/** + * Gets the static name of a function AST node. For function declarations it is + * easy. For anonymous function expressions it is much harder. If you search for + * `IsAnonymousFunctionDefinition()` in the ECMAScript spec you'll find places + * where JS gives anonymous function expressions names. We roughly detect the + * same AST nodes with some exceptions to better fit our use case. + */ +function getFunctionName(node) { + var _a, _b, _c, _d; + if (node.type === 'FunctionDeclaration' || + (node.type === 'FunctionExpression' && node.id)) { + // function useHook() {} + // const whatever = function useHook() {}; + // + // Function declaration or function expression names win over any + // assignment statements or other renames. + return node.id; + } + else if (node.type === 'FunctionExpression' || + node.type === 'ArrowFunctionExpression') { + if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.type) === 'VariableDeclarator' && + node.parent.init === node) { + // const useHook = () => {}; + return node.parent.id; + } + else if (((_b = node.parent) === null || _b === void 0 ? void 0 : _b.type) === 'AssignmentExpression' && + node.parent.right === node && + node.parent.operator === '=') { + // useHook = () => {}; + return node.parent.left; + } + else if (((_c = node.parent) === null || _c === void 0 ? void 0 : _c.type) === 'Property' && + node.parent.value === node && + !node.parent.computed) { + // {useHook: () => {}} + // {useHook() {}} + return node.parent.key; + // NOTE: We could also support `ClassProperty` and `MethodDefinition` + // here to be pedantic. However, hooks in a class are an anti-pattern. So + // we don't allow it to error early. + // + // class {useHook = () => {}} + // class {useHook() {}} + } + else if (((_d = node.parent) === null || _d === void 0 ? void 0 : _d.type) === 'AssignmentPattern' && + node.parent.right === node && + // @ts-expect-error Property computed does not exist on type `AssignmentPattern`. + !node.parent.computed) { + // const {useHook = () => {}} = {}; + // ({useHook = () => {}} = {}); + // + // Kinda clowny, but we'd said we'd follow spec convention for + // `IsAnonymousFunctionDefinition()` usage. + return node.parent.left; + } + else { + return undefined; + } + } + else { + return undefined; + } +} +/** + * Convenience function for peeking the last item in a stack. + */ +function last(array) { + return array[array.length - 1]; +} + +var rule = { + meta: { + type: 'suggestion', + docs: { + description: 'verifies the list of dependencies for Hooks like useEffect and similar', + recommended: true, + url: 'https://github.com/facebook/react/issues/14920', + }, + fixable: 'code', + hasSuggestions: true, + schema: [ + { + type: 'object', + additionalProperties: false, + enableDangerousAutofixThisMayCauseInfiniteLoops: false, + properties: { + additionalHooks: { + type: 'string', + }, + enableDangerousAutofixThisMayCauseInfiniteLoops: { + type: 'boolean', + }, + }, + }, + ], + }, + create: function (context) { + // Parse the `additionalHooks` regex. + var additionalHooks = context.options && + context.options[0] && + context.options[0].additionalHooks + ? new RegExp(context.options[0].additionalHooks) + : undefined; + var enableDangerousAutofixThisMayCauseInfiniteLoops = (context.options && + context.options[0] && + context.options[0].enableDangerousAutofixThisMayCauseInfiniteLoops) || + false; + var options = { + additionalHooks: additionalHooks, + enableDangerousAutofixThisMayCauseInfiniteLoops: enableDangerousAutofixThisMayCauseInfiniteLoops, + }; + function reportProblem(problem) { + if (enableDangerousAutofixThisMayCauseInfiniteLoops) { + // Used to enable legacy behavior. Dangerous. + // Keep this as an option until major IDEs upgrade (including VSCode FB ESLint extension). + if (Array.isArray(problem.suggest) && + problem.suggest.length > 0 && + problem.suggest[0]) { + problem.fix = problem.suggest[0].fix; + } + } + context.report(problem); + } + /** + * SourceCode that also works down to ESLint 3.0.0 + */ + var getSourceCode = typeof context.getSourceCode === 'function' + ? function () { + return context.getSourceCode(); + } + : function () { + return context.sourceCode; + }; + /** + * SourceCode#getScope that also works down to ESLint 3.0.0 + */ + var getScope = typeof context.getScope === 'function' + ? function () { + return context.getScope(); + } + : function (node) { + return context.sourceCode.getScope(node); + }; + var scopeManager = getSourceCode().scopeManager; + // Should be shared between visitors. + var setStateCallSites = new WeakMap(); + var stateVariables = new WeakSet(); + var stableKnownValueCache = new WeakMap(); + var functionWithoutCapturedValueCache = new WeakMap(); + var useEffectEventVariables = new WeakSet(); + function memoizeWithWeakMap(fn, map) { + return function (arg) { + if (map.has(arg)) { + // to verify cache hits: + // console.log(arg.name) + return map.get(arg); + } + var result = fn(arg); + map.set(arg, result); + return result; + }; + } + /** + * Visitor for both function expressions and arrow function expressions. + */ + function visitFunctionWithDependencies(node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect) { + var e_1, _a, e_2, _b, e_3, _c; + if (isEffect && node.async) { + reportProblem({ + node: node, + message: "Effect callbacks are synchronous to prevent race conditions. " + + "Put the async function inside:\n\n" + + 'useEffect(() => {\n' + + ' async function fetchData() {\n' + + ' // You can await here\n' + + ' const response = await MyAPI.getData(someId);\n' + + ' // ...\n' + + ' }\n' + + ' fetchData();\n' + + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + + 'Learn more about data fetching with Hooks: https://react.dev/link/hooks-data-fetching', + }); + } + // Get the current scope. + var scope = scopeManager.acquire(node); + if (!scope) { + throw new Error('Unable to acquire scope for the current node. This is a bug in eslint-plugin-react-hooks, please file an issue.'); + } + // Find all our "pure scopes". On every re-render of a component these + // pure scopes may have changes to the variables declared within. So all + // variables used in our reactive hook callback but declared in a pure + // scope need to be listed as dependencies of our reactive hook callback. + // + // According to the rules of React you can't read a mutable value in pure + // scope. We can't enforce this in a lint so we trust that all variables + // declared outside of pure scope are indeed frozen. + var pureScopes = new Set(); + var componentScope = null; + { + var currentScope = scope.upper; + while (currentScope) { + pureScopes.add(currentScope); + if (currentScope.type === 'function') { + break; + } + currentScope = currentScope.upper; + } + // If there is no parent function scope then there are no pure scopes. + // The ones we've collected so far are incorrect. So don't continue with + // the lint. + if (!currentScope) { + return; + } + componentScope = currentScope; + } + var isArray = Array.isArray; + // Next we'll define a few helpers that helps us + // tell if some values don't have to be declared as deps. + // Some are known to be stable based on Hook calls. + // const [state, setState] = useState() / React.useState() + // ^^^ true for this reference + // const [state, dispatch] = useReducer() / React.useReducer() + // ^^^ true for this reference + // const [state, dispatch] = useActionState() / React.useActionState() + // ^^^ true for this reference + // const ref = useRef() + // ^^^ true for this reference + // const onStuff = useEffectEvent(() => {}) + // ^^^ true for this reference + // False for everything else. + function isStableKnownHookValue(resolved) { + var e_4, _a, e_5, _b, e_6, _c; + if (!isArray(resolved.defs)) { + return false; + } + var def = resolved.defs[0]; + if (def == null) { + return false; + } + // Look for `let stuff = ...` + var defNode = def.node; + if (defNode.type !== 'VariableDeclarator') { + return false; + } + var init = defNode.init; + if (init == null) { + return false; + } + while (init.type === 'TSAsExpression' || init.type === 'AsExpression') { + init = init.expression; + } + // Detect primitive constants + // const foo = 42 + var declaration = defNode.parent; + if (declaration == null && componentScope != null) { + // This might happen if variable is declared after the callback. + // In that case ESLint won't set up .parent refs. + // So we'll set them up manually. + fastFindReferenceWithParent(componentScope.block, def.node.id); + declaration = def.node.parent; + if (declaration == null) { + return false; + } + } + if (declaration != null && + 'kind' in declaration && + declaration.kind === 'const' && + init.type === 'Literal' && + (typeof init.value === 'string' || + typeof init.value === 'number' || + init.value === null)) { + // Definitely stable + return true; + } + // Detect known Hook calls + // const [_, setState] = useState() + if (init.type !== 'CallExpression') { + return false; + } + var callee = init.callee; + // Step into `= React.something` initializer. + if (callee.type === 'MemberExpression' && + 'name' in callee.object && + callee.object.name === 'React' && + callee.property != null && + !callee.computed) { + callee = callee.property; + } + if (callee.type !== 'Identifier') { + return false; + } + var definitionNode = def.node; + var id = definitionNode.id; + var name = callee.name; + if (name === 'useRef' && id.type === 'Identifier') { + // useRef() return value is stable. + return true; + } + else if (isUseEffectEventIdentifier() && + id.type === 'Identifier') { + try { + for (var _d = __values(resolved.references), _e = _d.next(); !_e.done; _e = _d.next()) { + var ref = _e.value; + // @ts-expect-error These types are not compatible (Reference and Identifier) + if (ref !== id) { + useEffectEventVariables.add(ref.identifier); + } + } + } + catch (e_4_1) { e_4 = { error: e_4_1 }; } + finally { + try { + if (_e && !_e.done && (_a = _d.return)) _a.call(_d); + } + finally { if (e_4) throw e_4.error; } + } + // useEffectEvent() return value is always unstable. + return true; + } + else if (name === 'useState' || + name === 'useReducer' || + name === 'useActionState') { + // Only consider second value in initializing tuple stable. + if (id.type === 'ArrayPattern' && + id.elements.length === 2 && + isArray(resolved.identifiers)) { + // Is second tuple value the same reference we're checking? + if (id.elements[1] === resolved.identifiers[0]) { + if (name === 'useState') { + var references = resolved.references; + var writeCount = 0; + try { + for (var references_2 = __values(references), references_2_1 = references_2.next(); !references_2_1.done; references_2_1 = references_2.next()) { + var reference = references_2_1.value; + if (reference.isWrite()) { + writeCount++; + } + if (writeCount > 1) { + return false; + } + setStateCallSites.set(reference.identifier, id.elements[0]); + } + } + catch (e_5_1) { e_5 = { error: e_5_1 }; } + finally { + try { + if (references_2_1 && !references_2_1.done && (_b = references_2.return)) _b.call(references_2); + } + finally { if (e_5) throw e_5.error; } + } + } + // Setter is stable. + return true; + } + else if (id.elements[0] === resolved.identifiers[0]) { + if (name === 'useState') { + var references = resolved.references; + try { + for (var references_3 = __values(references), references_3_1 = references_3.next(); !references_3_1.done; references_3_1 = references_3.next()) { + var reference = references_3_1.value; + stateVariables.add(reference.identifier); + } + } + catch (e_6_1) { e_6 = { error: e_6_1 }; } + finally { + try { + if (references_3_1 && !references_3_1.done && (_c = references_3.return)) _c.call(references_3); + } + finally { if (e_6) throw e_6.error; } + } + } + // State variable itself is dynamic. + return false; + } + } + } + else if (name === 'useTransition') { + // Only consider second value in initializing tuple stable. + if (id.type === 'ArrayPattern' && + id.elements.length === 2 && + Array.isArray(resolved.identifiers)) { + // Is second tuple value the same reference we're checking? + if (id.elements[1] === resolved.identifiers[0]) { + // Setter is stable. + return true; + } + } + } + // By default assume it's dynamic. + return false; + } + // Some are just functions that don't reference anything dynamic. + function isFunctionWithoutCapturedValues(resolved) { + var e_7, _a, e_8, _b; + if (!isArray(resolved.defs)) { + return false; + } + var def = resolved.defs[0]; + if (def == null) { + return false; + } + if (def.node == null || def.node.id == null) { + return false; + } + // Search the direct component subscopes for + // top-level function definitions matching this reference. + var fnNode = def.node; + var childScopes = (componentScope === null || componentScope === void 0 ? void 0 : componentScope.childScopes) || []; + var fnScope = null; + try { + for (var childScopes_1 = __values(childScopes), childScopes_1_1 = childScopes_1.next(); !childScopes_1_1.done; childScopes_1_1 = childScopes_1.next()) { + var childScope = childScopes_1_1.value; + var childScopeBlock = childScope.block; + if ( + // function handleChange() {} + (fnNode.type === 'FunctionDeclaration' && + childScopeBlock === fnNode) || + // const handleChange = () => {} + // const handleChange = function() {} + (fnNode.type === 'VariableDeclarator' && + childScopeBlock.parent === fnNode)) { + // Found it! + fnScope = childScope; + break; + } + } + } + catch (e_7_1) { e_7 = { error: e_7_1 }; } + finally { + try { + if (childScopes_1_1 && !childScopes_1_1.done && (_a = childScopes_1.return)) _a.call(childScopes_1); + } + finally { if (e_7) throw e_7.error; } + } + if (fnScope == null) { + return false; + } + try { + // Does this function capture any values + // that are in pure scopes (aka render)? + for (var _c = __values(fnScope.through), _d = _c.next(); !_d.done; _d = _c.next()) { + var ref = _d.value; + if (ref.resolved == null) { + continue; + } + if (pureScopes.has(ref.resolved.scope) && + // Stable values are fine though, + // although we won't check functions deeper. + !memoizedIsStableKnownHookValue(ref.resolved)) { + return false; + } + } + } + catch (e_8_1) { e_8 = { error: e_8_1 }; } + finally { + try { + if (_d && !_d.done && (_b = _c.return)) _b.call(_c); + } + finally { if (e_8) throw e_8.error; } + } + // If we got here, this function doesn't capture anything + // from render--or everything it captures is known stable. + return true; + } + // Remember such values. Avoid re-running extra checks on them. + var memoizedIsStableKnownHookValue = memoizeWithWeakMap(isStableKnownHookValue, stableKnownValueCache); + var memoizedIsFunctionWithoutCapturedValues = memoizeWithWeakMap(isFunctionWithoutCapturedValues, functionWithoutCapturedValueCache); + // These are usually mistaken. Collect them. + var currentRefsInEffectCleanup = new Map(); + // Is this reference inside a cleanup function for this effect node? + // We can check by traversing scopes upwards from the reference, and checking + // if the last "return () => " we encounter is located directly inside the effect. + function isInsideEffectCleanup(reference) { + var curScope = reference.from; + var isInReturnedFunction = false; + while (curScope != null && curScope.block !== node) { + if (curScope.type === 'function') { + isInReturnedFunction = + curScope.block.parent != null && + curScope.block.parent.type === 'ReturnStatement'; + } + curScope = curScope.upper; + } + return isInReturnedFunction; + } + // Get dependencies from all our resolved references in pure scopes. + // Key is dependency string, value is whether it's stable. + var dependencies = new Map(); + var optionalChains = new Map(); + gatherDependenciesRecursively(scope); + function gatherDependenciesRecursively(currentScope) { + var e_9, _a, e_10, _b; + var _c, _d, _e, _f, _g; + try { + for (var _h = __values(currentScope.references), _j = _h.next(); !_j.done; _j = _h.next()) { + var reference = _j.value; + // If this reference is not resolved or it is not declared in a pure + // scope then we don't care about this reference. + if (!reference.resolved) { + continue; + } + if (!pureScopes.has(reference.resolved.scope)) { + continue; + } + // Narrow the scope of a dependency if it is, say, a member expression. + // Then normalize the narrowed dependency. + var referenceNode = fastFindReferenceWithParent(node, reference.identifier); + if (referenceNode == null) { + continue; + } + var dependencyNode = getDependency(referenceNode); + var dependency = analyzePropertyChain(dependencyNode, optionalChains); + // Accessing ref.current inside effect cleanup is bad. + if ( + // We're in an effect... + isEffect && + // ... and this look like accessing .current... + dependencyNode.type === 'Identifier' && + (((_c = dependencyNode.parent) === null || _c === void 0 ? void 0 : _c.type) === 'MemberExpression' || + ((_d = dependencyNode.parent) === null || _d === void 0 ? void 0 : _d.type) === 'OptionalMemberExpression') && + !dependencyNode.parent.computed && + dependencyNode.parent.property.type === 'Identifier' && + dependencyNode.parent.property.name === 'current' && + // ...in a cleanup function or below... + isInsideEffectCleanup(reference)) { + currentRefsInEffectCleanup.set(dependency, { + reference: reference, + dependencyNode: dependencyNode, + }); + } + if (((_e = dependencyNode.parent) === null || _e === void 0 ? void 0 : _e.type) === 'TSTypeQuery' || + ((_f = dependencyNode.parent) === null || _f === void 0 ? void 0 : _f.type) === 'TSTypeReference') { + continue; + } + var def = reference.resolved.defs[0]; + if (def == null) { + continue; + } + // Ignore references to the function itself as it's not defined yet. + if (def.node != null && def.node.init === node.parent) { + continue; + } + // Ignore Flow type parameters + // @ts-expect-error We don't have flow types + if (def.type === 'TypeParameter') { + continue; + } + // Add the dependency to a map so we can make sure it is referenced + // again in our dependencies array. Remember whether it's stable. + if (!dependencies.has(dependency)) { + var resolved = reference.resolved; + var isStable = memoizedIsStableKnownHookValue(resolved) || + memoizedIsFunctionWithoutCapturedValues(resolved); + dependencies.set(dependency, { + isStable: isStable, + references: [reference], + }); + } + else { + (_g = dependencies.get(dependency)) === null || _g === void 0 ? void 0 : _g.references.push(reference); + } + } + } + catch (e_9_1) { e_9 = { error: e_9_1 }; } + finally { + try { + if (_j && !_j.done && (_a = _h.return)) _a.call(_h); + } + finally { if (e_9) throw e_9.error; } + } + try { + for (var _k = __values(currentScope.childScopes), _l = _k.next(); !_l.done; _l = _k.next()) { + var childScope = _l.value; + gatherDependenciesRecursively(childScope); + } + } + catch (e_10_1) { e_10 = { error: e_10_1 }; } + finally { + try { + if (_l && !_l.done && (_b = _k.return)) _b.call(_k); + } + finally { if (e_10) throw e_10.error; } + } + } + // Warn about accessing .current in cleanup effects. + currentRefsInEffectCleanup.forEach(function (_a, dependency) { + var e_11, _b; + var _c, _d; + var reference = _a.reference, dependencyNode = _a.dependencyNode; + var references = ((_c = reference.resolved) === null || _c === void 0 ? void 0 : _c.references) || []; + // Is React managing this ref or us? + // Let's see if we can find a .current assignment. + var foundCurrentAssignment = false; + try { + for (var references_4 = __values(references), references_4_1 = references_4.next(); !references_4_1.done; references_4_1 = references_4.next()) { + var ref = references_4_1.value; + var identifier = ref.identifier; + var parent = identifier.parent; + if (parent != null && + // ref.current + // Note: no need to handle OptionalMemberExpression because it can't be LHS. + parent.type === 'MemberExpression' && + !parent.computed && + parent.property.type === 'Identifier' && + parent.property.name === 'current' && + // ref.current = + ((_d = parent.parent) === null || _d === void 0 ? void 0 : _d.type) === 'AssignmentExpression' && + parent.parent.left === parent) { + foundCurrentAssignment = true; + break; + } + } + } + catch (e_11_1) { e_11 = { error: e_11_1 }; } + finally { + try { + if (references_4_1 && !references_4_1.done && (_b = references_4.return)) _b.call(references_4); + } + finally { if (e_11) throw e_11.error; } + } + // We only want to warn about React-managed refs. + if (foundCurrentAssignment) { + return; + } + reportProblem({ + // @ts-expect-error We can do better here (dependencyNode.parent has not been type narrowed) + node: dependencyNode.parent.property, + message: "The ref value '".concat(dependency, ".current' will likely have ") + + "changed by the time this effect cleanup function runs. If " + + "this ref points to a node rendered by React, copy " + + "'".concat(dependency, ".current' to a variable inside the effect, and ") + + "use that variable in the cleanup function.", + }); + }); + // Warn about assigning to variables in the outer scope. + // Those are usually bugs. + var staleAssignments = new Set(); + function reportStaleAssignment(writeExpr, key) { + if (staleAssignments.has(key)) { + return; + } + staleAssignments.add(key); + reportProblem({ + node: writeExpr, + message: "Assignments to the '".concat(key, "' variable from inside React Hook ") + + "".concat(getSourceCode().getText(reactiveHook), " will be lost after each ") + + "render. To preserve the value over time, store it in a useRef " + + "Hook and keep the mutable value in the '.current' property. " + + "Otherwise, you can move this variable directly inside " + + "".concat(getSourceCode().getText(reactiveHook), "."), + }); + } + // Remember which deps are stable and report bad usage first. + var stableDependencies = new Set(); + dependencies.forEach(function (_a, key) { + var isStable = _a.isStable, references = _a.references; + if (isStable) { + stableDependencies.add(key); + } + references.forEach(function (reference) { + if (reference.writeExpr) { + reportStaleAssignment(reference.writeExpr, key); + } + }); + }); + if (staleAssignments.size > 0) { + // The intent isn't clear so we'll wait until you fix those first. + return; + } + if (!declaredDependenciesNode) { + // Check if there are any top-level setState() calls. + // Those tend to lead to infinite loops. + var setStateInsideEffectWithoutDeps_1 = null; + dependencies.forEach(function (_a, key) { + var references = _a.references; + if (setStateInsideEffectWithoutDeps_1) { + return; + } + references.forEach(function (reference) { + if (setStateInsideEffectWithoutDeps_1) { + return; + } + var id = reference.identifier; + var isSetState = setStateCallSites.has(id); + if (!isSetState) { + return; + } + var fnScope = reference.from; + while (fnScope != null && fnScope.type !== 'function') { + fnScope = fnScope.upper; + } + var isDirectlyInsideEffect = (fnScope === null || fnScope === void 0 ? void 0 : fnScope.block) === node; + if (isDirectlyInsideEffect) { + // TODO: we could potentially ignore early returns. + setStateInsideEffectWithoutDeps_1 = key; + } + }); + }); + if (setStateInsideEffectWithoutDeps_1) { + var suggestedDependencies_1 = collectRecommendations({ + dependencies: dependencies, + declaredDependencies: [], + stableDependencies: stableDependencies, + externalDependencies: new Set(), + isEffect: true, + }).suggestedDependencies; + reportProblem({ + node: reactiveHook, + message: "React Hook ".concat(reactiveHookName, " contains a call to '").concat(setStateInsideEffectWithoutDeps_1, "'. ") + + "Without a list of dependencies, this can lead to an infinite chain of updates. " + + "To fix this, pass [" + + suggestedDependencies_1.join(', ') + + "] as a second argument to the ".concat(reactiveHookName, " Hook."), + suggest: [ + { + desc: "Add dependencies array: [".concat(suggestedDependencies_1.join(', '), "]"), + fix: function (fixer) { + return fixer.insertTextAfter(node, ", [".concat(suggestedDependencies_1.join(', '), "]")); + }, + }, + ], + }); + } + return; + } + var declaredDependencies = []; + var externalDependencies = new Set(); + var isArrayExpression = declaredDependenciesNode.type === 'ArrayExpression'; + var isTSAsArrayExpression = declaredDependenciesNode.type === 'TSAsExpression' && + declaredDependenciesNode.expression.type === 'ArrayExpression'; + if (!isArrayExpression && !isTSAsArrayExpression) { + // If the declared dependencies are not an array expression then we + // can't verify that the user provided the correct dependencies. Tell + // the user this in an error. + reportProblem({ + node: declaredDependenciesNode, + message: "React Hook ".concat(getSourceCode().getText(reactiveHook), " was passed a ") + + 'dependency list that is not an array literal. This means we ' + + "can't statically verify whether you've passed the correct " + + 'dependencies.', + }); + } + else { + var arrayExpression = isTSAsArrayExpression + ? declaredDependenciesNode.expression + : declaredDependenciesNode; + arrayExpression.elements.forEach(function (declaredDependencyNode) { + // Skip elided elements. + if (declaredDependencyNode === null) { + return; + } + // If we see a spread element then add a special warning. + if (declaredDependencyNode.type === 'SpreadElement') { + reportProblem({ + node: declaredDependencyNode, + message: "React Hook ".concat(getSourceCode().getText(reactiveHook), " has a spread ") + + "element in its dependency array. This means we can't " + + "statically verify whether you've passed the " + + 'correct dependencies.', + }); + return; + } + if (useEffectEventVariables.has(declaredDependencyNode)) { + reportProblem({ + node: declaredDependencyNode, + message: 'Functions returned from `useEffectEvent` must not be included in the dependency array. ' + + "Remove `".concat(getSourceCode().getText(declaredDependencyNode), "` from the list."), + suggest: [ + { + desc: "Remove the dependency `".concat(getSourceCode().getText(declaredDependencyNode), "`"), + fix: function (fixer) { + return fixer.removeRange(declaredDependencyNode.range); + }, + }, + ], + }); + } + // Try to normalize the declared dependency. If we can't then an error + // will be thrown. We will catch that error and report an error. + var declaredDependency; + try { + declaredDependency = analyzePropertyChain(declaredDependencyNode, null); + } + catch (error) { + if (error instanceof Error && + /Unsupported node type/.test(error.message)) { + if (declaredDependencyNode.type === 'Literal') { + if (declaredDependencyNode.value && + dependencies.has(declaredDependencyNode.value)) { + reportProblem({ + node: declaredDependencyNode, + message: "The ".concat(declaredDependencyNode.raw, " literal is not a valid dependency ") + + "because it never changes. " + + "Did you mean to include ".concat(declaredDependencyNode.value, " in the array instead?"), + }); + } + else { + reportProblem({ + node: declaredDependencyNode, + message: "The ".concat(declaredDependencyNode.raw, " literal is not a valid dependency ") + + 'because it never changes. You can safely remove it.', + }); + } + } + else { + reportProblem({ + node: declaredDependencyNode, + message: "React Hook ".concat(getSourceCode().getText(reactiveHook), " has a ") + + "complex expression in the dependency array. " + + 'Extract it to a separate variable so it can be statically checked.', + }); + } + return; + } + else { + throw error; + } + } + var maybeID = declaredDependencyNode; + while (maybeID.type === 'MemberExpression' || + maybeID.type === 'OptionalMemberExpression' || + maybeID.type === 'ChainExpression') { + // @ts-expect-error This can be done better + maybeID = maybeID.object || maybeID.expression.object; + } + var isDeclaredInComponent = !componentScope.through.some(function (ref) { return ref.identifier === maybeID; }); + // Add the dependency to our declared dependency map. + declaredDependencies.push({ + key: declaredDependency, + node: declaredDependencyNode, + }); + if (!isDeclaredInComponent) { + externalDependencies.add(declaredDependency); + } + }); + } + var _d = collectRecommendations({ + dependencies: dependencies, + declaredDependencies: declaredDependencies, + stableDependencies: stableDependencies, + externalDependencies: externalDependencies, + isEffect: isEffect, + }), suggestedDependencies = _d.suggestedDependencies, unnecessaryDependencies = _d.unnecessaryDependencies, missingDependencies = _d.missingDependencies, duplicateDependencies = _d.duplicateDependencies; + var suggestedDeps = suggestedDependencies; + var problemCount = duplicateDependencies.size + + missingDependencies.size + + unnecessaryDependencies.size; + if (problemCount === 0) { + // If nothing else to report, check if some dependencies would + // invalidate on every render. + var constructions = scanForConstructions({ + declaredDependencies: declaredDependencies, + declaredDependenciesNode: declaredDependenciesNode, + componentScope: componentScope, + scope: scope, + }); + constructions.forEach(function (_a) { + var _b; + var construction = _a.construction, isUsedOutsideOfHook = _a.isUsedOutsideOfHook, depType = _a.depType; + var wrapperHook = depType === 'function' ? 'useCallback' : 'useMemo'; + var constructionType = depType === 'function' ? 'definition' : 'initialization'; + var defaultAdvice = "wrap the ".concat(constructionType, " of '").concat(construction.name.name, "' in its own ").concat(wrapperHook, "() Hook."); + var advice = isUsedOutsideOfHook + ? "To fix this, ".concat(defaultAdvice) + : "Move it inside the ".concat(reactiveHookName, " callback. Alternatively, ").concat(defaultAdvice); + var causation = depType === 'conditional' || depType === 'logical expression' + ? 'could make' + : 'makes'; + var message = "The '".concat(construction.name.name, "' ").concat(depType, " ").concat(causation, " the dependencies of ") + + "".concat(reactiveHookName, " Hook (at line ").concat((_b = declaredDependenciesNode.loc) === null || _b === void 0 ? void 0 : _b.start.line, ") ") + + "change on every render. ".concat(advice); + var suggest; + // Only handle the simple case of variable assignments. + // Wrapping function declarations can mess up hoisting. + if (isUsedOutsideOfHook && + construction.type === 'Variable' && + // Objects may be mutated after construction, which would make this + // fix unsafe. Functions _probably_ won't be mutated, so we'll + // allow this fix for them. + depType === 'function') { + suggest = [ + { + desc: "Wrap the ".concat(constructionType, " of '").concat(construction.name.name, "' in its own ").concat(wrapperHook, "() Hook."), + fix: function (fixer) { + var _a = __read(wrapperHook === 'useMemo' + ? ["useMemo(() => { return ", '; })'] + : ['useCallback(', ')'], 2), before = _a[0], after = _a[1]; + return [ + // TODO: also add an import? + fixer.insertTextBefore(construction.node.init, before), + // TODO: ideally we'd gather deps here but it would require + // restructuring the rule code. This will cause a new lint + // error to appear immediately for useCallback. Note we're + // not adding [] because would that changes semantics. + fixer.insertTextAfter(construction.node.init, after), + ]; + }, + }, + ]; + } + // TODO: What if the function needs to change on every render anyway? + // Should we suggest removing effect deps as an appropriate fix too? + reportProblem({ + // TODO: Why not report this at the dependency site? + node: construction.node, + message: message, + suggest: suggest, + }); + }); + return; + } + // If we're going to report a missing dependency, + // we might as well recalculate the list ignoring + // the currently specified deps. This can result + // in some extra deduplication. We can't do this + // for effects though because those have legit + // use cases for over-specifying deps. + if (!isEffect && missingDependencies.size > 0) { + suggestedDeps = collectRecommendations({ + dependencies: dependencies, + declaredDependencies: [], // Pretend we don't know + stableDependencies: stableDependencies, + externalDependencies: externalDependencies, + isEffect: isEffect, + }).suggestedDependencies; + } + // Alphabetize the suggestions, but only if deps were already alphabetized. + function areDeclaredDepsAlphabetized() { + if (declaredDependencies.length === 0) { + return true; + } + var declaredDepKeys = declaredDependencies.map(function (dep) { return dep.key; }); + var sortedDeclaredDepKeys = declaredDepKeys.slice().sort(); + return declaredDepKeys.join(',') === sortedDeclaredDepKeys.join(','); + } + if (areDeclaredDepsAlphabetized()) { + suggestedDeps.sort(); + } + // Most of our algorithm deals with dependency paths with optional chaining stripped. + // This function is the last step before printing a dependency, so now is a good time to + // check whether any members in our path are always used as optional-only. In that case, + // we will use ?. instead of . to concatenate those parts of the path. + function formatDependency(path) { + var members = path.split('.'); + var finalPath = ''; + for (var i = 0; i < members.length; i++) { + if (i !== 0) { + var pathSoFar = members.slice(0, i + 1).join('.'); + var isOptional = optionalChains.get(pathSoFar) === true; + finalPath += isOptional ? '?.' : '.'; + } + finalPath += members[i]; + } + return finalPath; + } + function getWarningMessage(deps, singlePrefix, label, fixVerb) { + if (deps.size === 0) { + return null; + } + return ((deps.size > 1 ? '' : singlePrefix + ' ') + + label + + ' ' + + (deps.size > 1 ? 'dependencies' : 'dependency') + + ': ' + + joinEnglish(Array.from(deps) + .sort() + .map(function (name) { return "'" + formatDependency(name) + "'"; })) + + ". Either ".concat(fixVerb, " ").concat(deps.size > 1 ? 'them' : 'it', " or remove the dependency array.")); + } + var extraWarning = ''; + if (unnecessaryDependencies.size > 0) { + var badRef_1 = null; + Array.from(unnecessaryDependencies.keys()).forEach(function (key) { + if (badRef_1 !== null) { + return; + } + if (key.endsWith('.current')) { + badRef_1 = key; + } + }); + if (badRef_1 !== null) { + extraWarning = + " Mutable values like '".concat(badRef_1, "' aren't valid dependencies ") + + "because mutating them doesn't re-render the component."; + } + else if (externalDependencies.size > 0) { + var dep = Array.from(externalDependencies)[0]; + // Don't show this warning for things that likely just got moved *inside* the callback + // because in that case they're clearly not referring to globals. + if (!scope.set.has(dep)) { + extraWarning = + " Outer scope values like '".concat(dep, "' aren't valid dependencies ") + + "because mutating them doesn't re-render the component."; + } + } + } + // `props.foo()` marks `props` as a dependency because it has + // a `this` value. This warning can be confusing. + // So if we're going to show it, append a clarification. + if (!extraWarning && missingDependencies.has('props')) { + var propDep = dependencies.get('props'); + if (propDep == null) { + return; + } + var refs = propDep.references; + if (!Array.isArray(refs)) { + return; + } + var isPropsOnlyUsedInMembers = true; + try { + for (var refs_1 = __values(refs), refs_1_1 = refs_1.next(); !refs_1_1.done; refs_1_1 = refs_1.next()) { + var ref = refs_1_1.value; + var id = fastFindReferenceWithParent(componentScope.block, ref.identifier); + if (!id) { + isPropsOnlyUsedInMembers = false; + break; + } + var parent = id.parent; + if (parent == null) { + isPropsOnlyUsedInMembers = false; + break; + } + if (parent.type !== 'MemberExpression' && + parent.type !== 'OptionalMemberExpression') { + isPropsOnlyUsedInMembers = false; + break; + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (refs_1_1 && !refs_1_1.done && (_a = refs_1.return)) _a.call(refs_1); + } + finally { if (e_1) throw e_1.error; } + } + if (isPropsOnlyUsedInMembers) { + extraWarning = + " However, 'props' will change when *any* prop changes, so the " + + "preferred fix is to destructure the 'props' object outside of " + + "the ".concat(reactiveHookName, " call and refer to those specific props ") + + "inside ".concat(getSourceCode().getText(reactiveHook), "."); + } + } + if (!extraWarning && missingDependencies.size > 0) { + // See if the user is trying to avoid specifying a callable prop. + // This usually means they're unaware of useCallback. + var missingCallbackDep_1 = null; + missingDependencies.forEach(function (missingDep) { + var e_12, _a; + var _b; + if (missingCallbackDep_1) { + return; + } + // Is this a variable from top scope? + var topScopeRef = componentScope.set.get(missingDep); + var usedDep = dependencies.get(missingDep); + if (!(usedDep === null || usedDep === void 0 ? void 0 : usedDep.references) || + ((_b = usedDep === null || usedDep === void 0 ? void 0 : usedDep.references[0]) === null || _b === void 0 ? void 0 : _b.resolved) !== topScopeRef) { + return; + } + // Is this a destructured prop? + var def = topScopeRef === null || topScopeRef === void 0 ? void 0 : topScopeRef.defs[0]; + if (def == null || def.name == null || def.type !== 'Parameter') { + return; + } + // Was it called in at least one case? Then it's a function. + var isFunctionCall = false; + var id; + try { + for (var _c = __values(usedDep.references), _d = _c.next(); !_d.done; _d = _c.next()) { + var reference = _d.value; + id = reference.identifier; + if (id != null && + id.parent != null && + (id.parent.type === 'CallExpression' || + id.parent.type === 'OptionalCallExpression') && + id.parent.callee === id) { + isFunctionCall = true; + break; + } + } + } + catch (e_12_1) { e_12 = { error: e_12_1 }; } + finally { + try { + if (_d && !_d.done && (_a = _c.return)) _a.call(_c); + } + finally { if (e_12) throw e_12.error; } + } + if (!isFunctionCall) { + return; + } + // If it's missing (i.e. in component scope) *and* it's a parameter + // then it is definitely coming from props destructuring. + // (It could also be props itself but we wouldn't be calling it then.) + missingCallbackDep_1 = missingDep; + }); + if (missingCallbackDep_1 !== null) { + extraWarning = + " If '".concat(missingCallbackDep_1, "' changes too often, ") + + "find the parent component that defines it " + + "and wrap that definition in useCallback."; + } + } + if (!extraWarning && missingDependencies.size > 0) { + var setStateRecommendation = null; + try { + for (var missingDependencies_1 = __values(missingDependencies), missingDependencies_1_1 = missingDependencies_1.next(); !missingDependencies_1_1.done; missingDependencies_1_1 = missingDependencies_1.next()) { + var missingDep = missingDependencies_1_1.value; + if (setStateRecommendation !== null) { + break; + } + var usedDep = dependencies.get(missingDep); + var references = usedDep.references; + var id = void 0; + var maybeCall = void 0; + try { + for (var references_1 = (e_3 = void 0, __values(references)), references_1_1 = references_1.next(); !references_1_1.done; references_1_1 = references_1.next()) { + var reference = references_1_1.value; + id = reference.identifier; + maybeCall = id.parent; + // Try to see if we have setState(someExpr(missingDep)). + while (maybeCall != null && maybeCall !== componentScope.block) { + if (maybeCall.type === 'CallExpression') { + var correspondingStateVariable = setStateCallSites.get(maybeCall.callee); + if (correspondingStateVariable != null) { + if ('name' in correspondingStateVariable && + correspondingStateVariable.name === missingDep) { + // setCount(count + 1) + setStateRecommendation = { + missingDep: missingDep, + setter: 'name' in maybeCall.callee ? maybeCall.callee.name : '', + form: 'updater', + }; + } + else if (stateVariables.has(id)) { + // setCount(count + increment) + setStateRecommendation = { + missingDep: missingDep, + setter: 'name' in maybeCall.callee ? maybeCall.callee.name : '', + form: 'reducer', + }; + } + else { + var resolved = reference.resolved; + if (resolved != null) { + // If it's a parameter *and* a missing dep, + // it must be a prop or something inside a prop. + // Therefore, recommend an inline reducer. + var def = resolved.defs[0]; + if (def != null && def.type === 'Parameter') { + setStateRecommendation = { + missingDep: missingDep, + setter: 'name' in maybeCall.callee + ? maybeCall.callee.name + : '', + form: 'inlineReducer', + }; + } + } + } + break; + } + } + maybeCall = maybeCall.parent; + } + if (setStateRecommendation !== null) { + break; + } + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (references_1_1 && !references_1_1.done && (_c = references_1.return)) _c.call(references_1); + } + finally { if (e_3) throw e_3.error; } + } + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (missingDependencies_1_1 && !missingDependencies_1_1.done && (_b = missingDependencies_1.return)) _b.call(missingDependencies_1); + } + finally { if (e_2) throw e_2.error; } + } + if (setStateRecommendation !== null) { + switch (setStateRecommendation.form) { + case 'reducer': + extraWarning = + " You can also replace multiple useState variables with useReducer " + + "if '".concat(setStateRecommendation.setter, "' needs the ") + + "current value of '".concat(setStateRecommendation.missingDep, "'."); + break; + case 'inlineReducer': + extraWarning = + " If '".concat(setStateRecommendation.setter, "' needs the ") + + "current value of '".concat(setStateRecommendation.missingDep, "', ") + + "you can also switch to useReducer instead of useState and " + + "read '".concat(setStateRecommendation.missingDep, "' in the reducer."); + break; + case 'updater': + extraWarning = + " You can also do a functional update '".concat(setStateRecommendation.setter, "(").concat(setStateRecommendation.missingDep.slice(0, 1), " => ...)' if you only need '").concat(setStateRecommendation.missingDep, "'") + " in the '".concat(setStateRecommendation.setter, "' call."); + break; + default: + throw new Error('Unknown case.'); + } + } + } + reportProblem({ + node: declaredDependenciesNode, + message: "React Hook ".concat(getSourceCode().getText(reactiveHook), " has ") + + // To avoid a long message, show the next actionable item. + (getWarningMessage(missingDependencies, 'a', 'missing', 'include') || + getWarningMessage(unnecessaryDependencies, 'an', 'unnecessary', 'exclude') || + getWarningMessage(duplicateDependencies, 'a', 'duplicate', 'omit')) + + extraWarning, + suggest: [ + { + desc: "Update the dependencies array to be: [".concat(suggestedDeps + .map(formatDependency) + .join(', '), "]"), + fix: function (fixer) { + // TODO: consider preserving the comments or formatting? + return fixer.replaceText(declaredDependenciesNode, "[".concat(suggestedDeps.map(formatDependency).join(', '), "]")); + }, + }, + ], + }); + } + function visitCallExpression(node) { + var callbackIndex = getReactiveHookCallbackIndex(node.callee, options); + if (callbackIndex === -1) { + // Not a React Hook call that needs deps. + return; + } + var callback = node.arguments[callbackIndex]; + var reactiveHook = node.callee; + var nodeWithoutNamespace = getNodeWithoutReactNamespace(reactiveHook); + var reactiveHookName = 'name' in nodeWithoutNamespace ? nodeWithoutNamespace.name : ''; + var maybeNode = node.arguments[callbackIndex + 1]; + var declaredDependenciesNode = maybeNode && + !(maybeNode.type === 'Identifier' && maybeNode.name === 'undefined') + ? maybeNode + : undefined; + var isEffect = /Effect($|[^a-z])/g.test(reactiveHookName); + // Check whether a callback is supplied. If there is no callback supplied + // then the hook will not work and React will throw a TypeError. + // So no need to check for dependency inclusion. + if (!callback) { + reportProblem({ + node: reactiveHook, + message: "React Hook ".concat(reactiveHookName, " requires an effect callback. ") + + "Did you forget to pass a callback to the hook?", + }); + return; + } + // Check the declared dependencies for this reactive hook. If there is no + // second argument then the reactive callback will re-run on every render. + // So no need to check for dependency inclusion. + if (!declaredDependenciesNode && !isEffect) { + // These are only used for optimization. + if (reactiveHookName === 'useMemo' || + reactiveHookName === 'useCallback') { + // TODO: Can this have a suggestion? + reportProblem({ + node: reactiveHook, + message: "React Hook ".concat(reactiveHookName, " does nothing when called with ") + + "only one argument. Did you forget to pass an array of " + + "dependencies?", + }); + } + return; + } + while (callback.type === 'TSAsExpression' || + callback.type === 'AsExpression') { + callback = callback.expression; + } + switch (callback.type) { + case 'FunctionExpression': + case 'ArrowFunctionExpression': + visitFunctionWithDependencies(callback, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect); + return; // Handled + case 'Identifier': + if (!declaredDependenciesNode) { + // No deps, no problems. + return; // Handled + } + // The function passed as a callback is not written inline. + // But perhaps it's in the dependencies array? + if ('elements' in declaredDependenciesNode && + declaredDependenciesNode.elements && + declaredDependenciesNode.elements.some(function (el) { return el && el.type === 'Identifier' && el.name === callback.name; })) { + // If it's already in the list of deps, we don't care because + // this is valid regardless. + return; // Handled + } + // We'll do our best effort to find it, complain otherwise. + var variable = getScope(callback).set.get(callback.name); + if (variable == null || variable.defs == null) { + // If it's not in scope, we don't care. + return; // Handled + } + // The function passed as a callback is not written inline. + // But it's defined somewhere in the render scope. + // We'll do our best effort to find and check it, complain otherwise. + var def = variable.defs[0]; + if (!def || !def.node) { + break; // Unhandled + } + if (def.type === 'Parameter') { + reportProblem({ + node: reactiveHook, + message: getUnknownDependenciesMessage(reactiveHookName), + }); + return; + } + if (def.type !== 'Variable' && def.type !== 'FunctionName') { + // Parameter or an unusual pattern. Bail out. + break; // Unhandled + } + switch (def.node.type) { + case 'FunctionDeclaration': + // useEffect(() => { ... }, []); + visitFunctionWithDependencies(def.node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect); + return; // Handled + case 'VariableDeclarator': + var init = def.node.init; + if (!init) { + break; // Unhandled + } + switch (init.type) { + // const effectBody = () => {...}; + // useEffect(effectBody, []); + case 'ArrowFunctionExpression': + case 'FunctionExpression': + // We can inspect this function as if it were inline. + visitFunctionWithDependencies(init, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect); + return; // Handled + } + break; // Unhandled + } + break; // Unhandled + default: + // useEffect(generateEffectBody(), []); + reportProblem({ + node: reactiveHook, + message: getUnknownDependenciesMessage(reactiveHookName), + }); + return; // Handled + } + // Something unusual. Fall back to suggesting to add the body itself as a dep. + reportProblem({ + node: reactiveHook, + message: "React Hook ".concat(reactiveHookName, " has a missing dependency: '").concat(callback.name, "'. ") + + "Either include it or remove the dependency array.", + suggest: [ + { + desc: "Update the dependencies array to be: [".concat(callback.name, "]"), + fix: function (fixer) { + return fixer.replaceText(declaredDependenciesNode, "[".concat(callback.name, "]")); + }, + }, + ], + }); + } + return { + CallExpression: visitCallExpression, + }; + }, +}; +// The meat of the logic. +function collectRecommendations(_a) { + var dependencies = _a.dependencies, declaredDependencies = _a.declaredDependencies, stableDependencies = _a.stableDependencies, externalDependencies = _a.externalDependencies, isEffect = _a.isEffect; + // Our primary data structure. + // It is a logical representation of property chains: + // `props` -> `props.foo` -> `props.foo.bar` -> `props.foo.bar.baz` + // -> `props.lol` + // -> `props.huh` -> `props.huh.okay` + // -> `props.wow` + // We'll use it to mark nodes that are *used* by the programmer, + // and the nodes that were *declared* as deps. Then we will + // traverse it to learn which deps are missing or unnecessary. + var depTree = createDepTree(); + function createDepTree() { + return { + isUsed: false, // True if used in code + isSatisfiedRecursively: false, // True if specified in deps + isSubtreeUsed: false, // True if something deeper is used by code + children: new Map(), // Nodes for properties + }; + } + // Mark all required nodes first. + // Imagine exclamation marks next to each used deep property. + dependencies.forEach(function (_, key) { + var node = getOrCreateNodeByPath(depTree, key); + node.isUsed = true; + markAllParentsByPath(depTree, key, function (parent) { + parent.isSubtreeUsed = true; + }); + }); + // Mark all satisfied nodes. + // Imagine checkmarks next to each declared dependency. + declaredDependencies.forEach(function (_a) { + var key = _a.key; + var node = getOrCreateNodeByPath(depTree, key); + node.isSatisfiedRecursively = true; + }); + stableDependencies.forEach(function (key) { + var node = getOrCreateNodeByPath(depTree, key); + node.isSatisfiedRecursively = true; + }); + // Tree manipulation helpers. + function getOrCreateNodeByPath(rootNode, path) { + var e_13, _a; + var keys = path.split('.'); + var node = rootNode; + try { + for (var keys_1 = __values(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) { + var key = keys_1_1.value; + var child = node.children.get(key); + if (!child) { + child = createDepTree(); + node.children.set(key, child); + } + node = child; + } + } + catch (e_13_1) { e_13 = { error: e_13_1 }; } + finally { + try { + if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return)) _a.call(keys_1); + } + finally { if (e_13) throw e_13.error; } + } + return node; + } + function markAllParentsByPath(rootNode, path, fn) { + var e_14, _a; + var keys = path.split('.'); + var node = rootNode; + try { + for (var keys_2 = __values(keys), keys_2_1 = keys_2.next(); !keys_2_1.done; keys_2_1 = keys_2.next()) { + var key = keys_2_1.value; + var child = node.children.get(key); + if (!child) { + return; + } + fn(child); + node = child; + } + } + catch (e_14_1) { e_14 = { error: e_14_1 }; } + finally { + try { + if (keys_2_1 && !keys_2_1.done && (_a = keys_2.return)) _a.call(keys_2); + } + finally { if (e_14) throw e_14.error; } + } + } + // Now we can learn which dependencies are missing or necessary. + var missingDependencies = new Set(); + var satisfyingDependencies = new Set(); + scanTreeRecursively(depTree, missingDependencies, satisfyingDependencies, function (key) { return key; }); + function scanTreeRecursively(node, missingPaths, satisfyingPaths, keyToPath) { + node.children.forEach(function (child, key) { + var path = keyToPath(key); + if (child.isSatisfiedRecursively) { + if (child.isSubtreeUsed) { + // Remember this dep actually satisfied something. + satisfyingPaths.add(path); + } + // It doesn't matter if there's something deeper. + // It would be transitively satisfied since we assume immutability. + // `props.foo` is enough if you read `props.foo.id`. + return; + } + if (child.isUsed) { + // Remember that no declared deps satisfied this node. + missingPaths.add(path); + // If we got here, nothing in its subtree was satisfied. + // No need to search further. + return; + } + scanTreeRecursively(child, missingPaths, satisfyingPaths, function (childKey) { return path + '.' + childKey; }); + }); + } + // Collect suggestions in the order they were originally specified. + var suggestedDependencies = []; + var unnecessaryDependencies = new Set(); + var duplicateDependencies = new Set(); + declaredDependencies.forEach(function (_a) { + var key = _a.key; + // Does this declared dep satisfy a real need? + if (satisfyingDependencies.has(key)) { + if (suggestedDependencies.indexOf(key) === -1) { + // Good one. + suggestedDependencies.push(key); + } + else { + // Duplicate. + duplicateDependencies.add(key); + } + } + else { + if (isEffect && + !key.endsWith('.current') && + !externalDependencies.has(key)) { + // Effects are allowed extra "unnecessary" deps. + // Such as resetting scroll when ID changes. + // Consider them legit. + // The exception is ref.current which is always wrong. + if (suggestedDependencies.indexOf(key) === -1) { + suggestedDependencies.push(key); + } + } + else { + // It's definitely not needed. + unnecessaryDependencies.add(key); + } + } + }); + // Then add the missing ones at the end. + missingDependencies.forEach(function (key) { + suggestedDependencies.push(key); + }); + return { + suggestedDependencies: suggestedDependencies, + unnecessaryDependencies: unnecessaryDependencies, + duplicateDependencies: duplicateDependencies, + missingDependencies: missingDependencies, + }; +} +// If the node will result in constructing a referentially unique value, return +// its human readable type name, else return null. +function getConstructionExpressionType(node) { + switch (node.type) { + case 'ObjectExpression': + return 'object'; + case 'ArrayExpression': + return 'array'; + case 'ArrowFunctionExpression': + case 'FunctionExpression': + return 'function'; + case 'ClassExpression': + return 'class'; + case 'ConditionalExpression': + if (getConstructionExpressionType(node.consequent) != null || + getConstructionExpressionType(node.alternate) != null) { + return 'conditional'; + } + return null; + case 'LogicalExpression': + if (getConstructionExpressionType(node.left) != null || + getConstructionExpressionType(node.right) != null) { + return 'logical expression'; + } + return null; + case 'JSXFragment': + return 'JSX fragment'; + case 'JSXElement': + return 'JSX element'; + case 'AssignmentExpression': + if (getConstructionExpressionType(node.right) != null) { + return 'assignment expression'; + } + return null; + case 'NewExpression': + return 'object construction'; + case 'Literal': + if (node.value instanceof RegExp) { + return 'regular expression'; + } + return null; + case 'TypeCastExpression': + case 'AsExpression': + case 'TSAsExpression': + return getConstructionExpressionType(node.expression); + } + return null; +} +// Finds variables declared as dependencies +// that would invalidate on every render. +function scanForConstructions(_a) { + var declaredDependencies = _a.declaredDependencies, declaredDependenciesNode = _a.declaredDependenciesNode, componentScope = _a.componentScope, scope = _a.scope; + var constructions = declaredDependencies + .map(function (_a) { + var key = _a.key; + var ref = componentScope.variables.find(function (v) { return v.name === key; }); + if (ref == null) { + return null; + } + var node = ref.defs[0]; + if (node == null) { + return null; + } + // const handleChange = function () {} + // const handleChange = () => {} + // const foo = {} + // const foo = [] + // etc. + if (node.type === 'Variable' && + node.node.type === 'VariableDeclarator' && + node.node.id.type === 'Identifier' && // Ensure this is not destructed assignment + node.node.init != null) { + var constantExpressionType = getConstructionExpressionType(node.node.init); + if (constantExpressionType) { + return [ref, constantExpressionType]; + } + } + // function handleChange() {} + if (node.type === 'FunctionName' && + node.node.type === 'FunctionDeclaration') { + return [ref, 'function']; + } + // class Foo {} + if (node.type === 'ClassName' && node.node.type === 'ClassDeclaration') { + return [ref, 'class']; + } + return null; + }) + .filter(Boolean); + function isUsedOutsideOfHook(ref) { + var e_15, _a; + var foundWriteExpr = false; + try { + for (var _b = __values(ref.references), _c = _b.next(); !_c.done; _c = _b.next()) { + var reference = _c.value; + if (reference.writeExpr) { + if (foundWriteExpr) { + // Two writes to the same function. + return true; + } + else { + // Ignore first write as it's not usage. + foundWriteExpr = true; + continue; + } + } + var currentScope = reference.from; + while (currentScope !== scope && currentScope != null) { + currentScope = currentScope.upper; + } + if (currentScope !== scope) { + // This reference is outside the Hook callback. + // It can only be legit if it's the deps array. + if (!isAncestorNodeOf(declaredDependenciesNode, reference.identifier)) { + return true; + } + } + } + } + catch (e_15_1) { e_15 = { error: e_15_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + } + finally { if (e_15) throw e_15.error; } + } + return false; + } + return constructions.map(function (_a) { + var _b = __read(_a, 2), ref = _b[0], depType = _b[1]; + return ({ + construction: ref.defs[0], + depType: depType, + isUsedOutsideOfHook: isUsedOutsideOfHook(ref), + }); + }); +} +/** + * Assuming () means the passed/returned node: + * (props) => (props) + * props.(foo) => (props.foo) + * props.foo.(bar) => (props).foo.bar + * props.foo.bar.(baz) => (props).foo.bar.baz + */ +function getDependency(node) { + if (node.parent && + (node.parent.type === 'MemberExpression' || + node.parent.type === 'OptionalMemberExpression') && + node.parent.object === node && + 'name' in node.parent.property && + node.parent.property.name !== 'current' && + !node.parent.computed && + !(node.parent.parent != null && + (node.parent.parent.type === 'CallExpression' || + node.parent.parent.type === 'OptionalCallExpression') && + node.parent.parent.callee === node.parent)) { + return getDependency(node.parent); + } + else if ( + // Note: we don't check OptionalMemberExpression because it can't be LHS. + node.type === 'MemberExpression' && + node.parent && + node.parent.type === 'AssignmentExpression' && + node.parent.left === node) { + return node.object; + } + else { + return node; + } +} +/** + * Mark a node as either optional or required. + * Note: If the node argument is an OptionalMemberExpression, it doesn't necessarily mean it is optional. + * It just means there is an optional member somewhere inside. + * This particular node might still represent a required member, so check .optional field. + */ +function markNode(node, optionalChains, result) { + if (optionalChains) { + if ('optional' in node && node.optional) { + // We only want to consider it optional if *all* usages were optional. + if (!optionalChains.has(result)) { + // Mark as (maybe) optional. If there's a required usage, this will be overridden. + optionalChains.set(result, true); + } + } + else { + // Mark as required. + optionalChains.set(result, false); + } + } +} +/** + * Assuming () means the passed node. + * (foo) -> 'foo' + * foo(.)bar -> 'foo.bar' + * foo.bar(.)baz -> 'foo.bar.baz' + * Otherwise throw. + */ +function analyzePropertyChain(node, optionalChains) { + if (node.type === 'Identifier' || node.type === 'JSXIdentifier') { + var result = node.name; + if (optionalChains) { + // Mark as required. + optionalChains.set(result, false); + } + return result; + } + else if (node.type === 'MemberExpression' && !node.computed) { + var object = analyzePropertyChain(node.object, optionalChains); + var property = analyzePropertyChain(node.property, null); + var result = "".concat(object, ".").concat(property); + markNode(node, optionalChains, result); + return result; + } + else if (node.type === 'OptionalMemberExpression' && !node.computed) { + var object = analyzePropertyChain(node.object, optionalChains); + var property = analyzePropertyChain(node.property, null); + var result = "".concat(object, ".").concat(property); + markNode(node, optionalChains, result); + return result; + } + else if (node.type === 'ChainExpression' && + (!('computed' in node) || !node.computed)) { + var expression = node.expression; + if (expression.type === 'CallExpression') { + throw new Error("Unsupported node type: ".concat(expression.type)); + } + var object = analyzePropertyChain(expression.object, optionalChains); + var property = analyzePropertyChain(expression.property, null); + var result = "".concat(object, ".").concat(property); + markNode(expression, optionalChains, result); + return result; + } + else { + throw new Error("Unsupported node type: ".concat(node.type)); + } +} +function getNodeWithoutReactNamespace(node) { + if (node.type === 'MemberExpression' && + node.object.type === 'Identifier' && + node.object.name === 'React' && + node.property.type === 'Identifier' && + !node.computed) { + return node.property; + } + return node; +} +// What's the index of callback that needs to be analyzed for a given Hook? +// -1 if it's not a Hook we care about (e.g. useState). +// 0 for useEffect/useMemo/useCallback(fn). +// 1 for useImperativeHandle(ref, fn). +// For additionally configured Hooks, assume that they're like useEffect (0). +function getReactiveHookCallbackIndex(calleeNode, options) { + var node = getNodeWithoutReactNamespace(calleeNode); + if (node.type !== 'Identifier') { + return -1; + } + switch (node.name) { + case 'useEffect': + case 'useLayoutEffect': + case 'useCallback': + case 'useMemo': + // useEffect(fn) + return 0; + case 'useImperativeHandle': + // useImperativeHandle(ref, fn) + return 1; + default: + if (node === calleeNode && options && options.additionalHooks) { + // Allow the user to provide a regular expression which enables the lint to + // target custom reactive hooks. + var name = void 0; + try { + name = analyzePropertyChain(node, null); + } + catch (error) { + if (error instanceof Error && + /Unsupported node type/.test(error.message)) { + return 0; + } + else { + throw error; + } + } + return options.additionalHooks.test(name) ? 0 : -1; + } + else { + return -1; + } + } +} +/** + * ESLint won't assign node.parent to references from context.getScope() + * + * So instead we search for the node from an ancestor assigning node.parent + * as we go. This mutates the AST. + * + * This traversal is: + * - optimized by only searching nodes with a range surrounding our target node + * - agnostic to AST node types, it looks for `{ type: string, ... }` + */ +function fastFindReferenceWithParent(start, target) { + var e_16, _a; + var queue = [start]; + var item; + while (queue.length) { + item = queue.shift(); + if (isSameIdentifier(item, target)) { + return item; + } + if (!isAncestorNodeOf(item, target)) { + continue; + } + try { + for (var _b = (e_16 = void 0, __values(Object.entries(item))), _c = _b.next(); !_c.done; _c = _b.next()) { + var _d = __read(_c.value, 2), key = _d[0], value = _d[1]; + if (key === 'parent') { + continue; + } + if (isNodeLike(value)) { + value.parent = item; + queue.push(value); + } + else if (Array.isArray(value)) { + value.forEach(function (val) { + if (isNodeLike(val)) { + val.parent = item; + queue.push(val); + } + }); + } + } + } + catch (e_16_1) { e_16 = { error: e_16_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + } + finally { if (e_16) throw e_16.error; } + } + } + return null; +} +function joinEnglish(arr) { + var s = ''; + for (var i = 0; i < arr.length; i++) { + s += arr[i]; + if (i === 0 && arr.length === 2) { + s += ' and '; + } + else if (i === arr.length - 2 && arr.length > 2) { + s += ', and '; + } + else if (i < arr.length - 1) { + s += ', '; + } + } + return s; +} +function isNodeLike(val) { + return (typeof val === 'object' && + val !== null && + !Array.isArray(val) && + 'type' in val && + typeof val.type === 'string'); +} +function isSameIdentifier(a, b) { + return ((a.type === 'Identifier' || a.type === 'JSXIdentifier') && + a.type === b.type && + a.name === b.name && + !!a.range && + !!b.range && + a.range[0] === b.range[0] && + a.range[1] === b.range[1]); +} +function isAncestorNodeOf(a, b) { + return (!!a.range && + !!b.range && + a.range[0] <= b.range[0] && + a.range[1] >= b.range[1]); +} +function isUseEffectEventIdentifier(node) { + return false; +} +function getUnknownDependenciesMessage(reactiveHookName) { + return ("React Hook ".concat(reactiveHookName, " received a function whose dependencies ") + + "are unknown. Pass an inline function instead."); +} + +// All rules +var rules = { + 'rules-of-hooks': rule$1, + 'exhaustive-deps': rule, +}; +// Config rules +var configRules = { + 'react-hooks/rules-of-hooks': 'error', + 'react-hooks/exhaustive-deps': 'warn', +}; +// Legacy config +var legacyRecommendedConfig = { + plugins: ['react-hooks'], + rules: configRules, +}; +// Plugin object +var plugin = { + // TODO: Make this more dynamic to populate version from package.json. + // This can be done by injecting at build time, since importing the package.json isn't an option in Meta + meta: { name: 'eslint-plugin-react-hooks' }, + rules: rules, + configs: { + /** Legacy recommended config, to be used with rc-based configurations */ + 'recommended-legacy': legacyRecommendedConfig, + /** + * 'recommended' is currently aliased to the legacy / rc recommended config) to maintain backwards compatibility. + * This is deprecated and in v6, it will switch to alias the flat recommended config. + */ + recommended: legacyRecommendedConfig, + /** Latest recommended config, to be used with flat configurations */ + 'recommended-latest': { + name: 'react-hooks/recommended', + plugins: { + get 'react-hooks'() { + return plugin; + }, + }, + rules: configRules, + }, + }, +}; +var configs = plugin.configs; +var meta = plugin.meta; +// TODO: If the plugin is ever updated to be pure ESM and drops support for rc-based configs, then it should be exporting the plugin as default +// instead of individual named exports. +// export default plugin; + +exports.configs = configs; +exports.meta = meta; +exports.rules = rules; diff --git a/node_modules/eslint-plugin-react-hooks/index.d.ts b/node_modules/eslint-plugin-react-hooks/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..62ca164ec2173a8212248d06a029b767f9ca281d --- /dev/null +++ b/node_modules/eslint-plugin-react-hooks/index.d.ts @@ -0,0 +1 @@ +export * from './cjs/eslint-plugin-react-hooks'; diff --git a/node_modules/eslint-plugin-react-hooks/index.js b/node_modules/eslint-plugin-react-hooks/index.js new file mode 100644 index 0000000000000000000000000000000000000000..20458a7a9bf22a914d6ac6ac4aaabe5acb31220e --- /dev/null +++ b/node_modules/eslint-plugin-react-hooks/index.js @@ -0,0 +1,9 @@ +'use strict'; + +// TODO: this doesn't make sense for an ESLint rule. +// We need to fix our build process to not create bundles for "raw" packages like this. +if (process.env.NODE_ENV === 'production') { + module.exports = require('./cjs/eslint-plugin-react-hooks.production.js'); +} else { + module.exports = require('./cjs/eslint-plugin-react-hooks.development.js'); +} diff --git a/node_modules/eslint-plugin-react-hooks/package.json b/node_modules/eslint-plugin-react-hooks/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d3717b9dee61c65cca7a53b83aacde21093934e6 --- /dev/null +++ b/node_modules/eslint-plugin-react-hooks/package.json @@ -0,0 +1,58 @@ +{ + "name": "eslint-plugin-react-hooks", + "description": "ESLint rules for React Hooks", + "version": "5.2.0", + "repository": { + "type": "git", + "url": "https://github.com/facebook/react.git", + "directory": "packages/eslint-plugin-react-hooks" + }, + "files": [ + "LICENSE", + "README.md", + "cjs", + "index.js", + "index.d.ts" + ], + "keywords": [ + "eslint", + "eslint-plugin", + "eslintplugin", + "react" + ], + "scripts": { + "test": "jest", + "typecheck": "tsc --noEmit" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/facebook/react/issues" + }, + "main": "./index.js", + "types": "./index.d.ts", + "engines": { + "node": ">=10" + }, + "homepage": "https://react.dev/", + "peerDependencies": { + "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0" + }, + "devDependencies": { + "@babel/eslint-parser": "^7.11.4", + "@babel/preset-typescript": "^7.26.0", + "@tsconfig/strictest": "^2.0.5", + "@typescript-eslint/parser-v2": "npm:@typescript-eslint/parser@^2.26.0", + "@typescript-eslint/parser-v3": "npm:@typescript-eslint/parser@^3.10.0", + "@typescript-eslint/parser-v4": "npm:@typescript-eslint/parser@^4.1.0", + "@typescript-eslint/parser-v5": "npm:@typescript-eslint/parser@^5.62.0", + "@types/eslint": "^8.56.12", + "@types/estree": "^1.0.6", + "@types/estree-jsx": "^1.0.5", + "@types/node": "^20.2.5", + "babel-eslint": "^10.0.3", + "eslint-v7": "npm:eslint@^7.7.0", + "eslint-v9": "npm:eslint@^9.0.0", + "jest": "^29.5.0", + "typescript": "^5.4.3" + } +} diff --git a/node_modules/eslint-plugin-react/node_modules/resolve/test/resolver.js b/node_modules/eslint-plugin-react/node_modules/resolve/test/resolver.js new file mode 100644 index 0000000000000000000000000000000000000000..a33931877d2ba56721a87a5e31a3a43e89ef6dd4 --- /dev/null +++ b/node_modules/eslint-plugin-react/node_modules/resolve/test/resolver.js @@ -0,0 +1,613 @@ +var path = require('path'); +var fs = require('fs'); +var test = require('tape'); +var resolve = require('../'); +var async = require('../async'); + +test('`./async` entry point', function (t) { + t.equal(resolve, async, '`./async` entry point is the same as `main`'); + t.end(); +}); + +test('async foo', function (t) { + t.plan(12); + var dir = path.join(__dirname, 'resolver'); + + resolve('./foo', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg && pkg.name, 'resolve'); + }); + + resolve('./foo.js', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg && pkg.name, 'resolve'); + }); + + resolve('./foo', { basedir: dir, 'package': { main: 'resolver' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg && pkg.main, 'resolver'); + }); + + resolve('./foo.js', { basedir: dir, 'package': { main: 'resolver' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg.main, 'resolver'); + }); + + resolve('./foo', { basedir: dir, filename: path.join(dir, 'baz.js') }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + }); + + resolve('foo', { basedir: dir }, function (err) { + t.equal(err.message, "Cannot find module 'foo' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + // Test that filename is reported as the "from" value when passed. + resolve('foo', { basedir: dir, filename: path.join(dir, 'baz.js') }, function (err) { + t.equal(err.message, "Cannot find module 'foo' from '" + path.join(dir, 'baz.js') + "'"); + }); +}); + +test('bar', function (t) { + t.plan(6); + var dir = path.join(__dirname, 'resolver'); + + resolve('foo', { basedir: dir + '/bar' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js')); + t.equal(pkg, undefined); + }); + + resolve('foo', { basedir: dir + '/bar' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js')); + t.equal(pkg, undefined); + }); + + resolve('foo', { basedir: dir + '/bar', 'package': { main: 'bar' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js')); + t.equal(pkg.main, 'bar'); + }); +}); + +test('baz', function (t) { + t.plan(4); + var dir = path.join(__dirname, 'resolver'); + + resolve('./baz', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'baz/quux.js')); + t.equal(pkg.main, 'quux.js'); + }); + + resolve('./baz', { basedir: dir, 'package': { main: 'resolver' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'baz/quux.js')); + t.equal(pkg.main, 'quux.js'); + }); +}); + +test('biz', function (t) { + t.plan(24); + var dir = path.join(__dirname, 'resolver/biz/node_modules'); + + resolve('./grux', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg, undefined); + }); + + resolve('./grux', { basedir: dir, 'package': { main: 'biz' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg.main, 'biz'); + }); + + resolve('./garply', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('./garply', { basedir: dir, 'package': { main: 'biz' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('tiv', { basedir: dir + '/grux' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg, undefined); + }); + + resolve('tiv', { basedir: dir + '/grux', 'package': { main: 'grux' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg.main, 'grux'); + }); + + resolve('tiv', { basedir: dir + '/garply' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg, undefined); + }); + + resolve('tiv', { basedir: dir + '/garply', 'package': { main: './lib' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('grux', { basedir: dir + '/tiv' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg, undefined); + }); + + resolve('grux', { basedir: dir + '/tiv', 'package': { main: 'tiv' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg.main, 'tiv'); + }); + + resolve('garply', { basedir: dir + '/tiv' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('garply', { basedir: dir + '/tiv', 'package': { main: 'tiv' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); +}); + +test('quux', function (t) { + t.plan(2); + var dir = path.join(__dirname, 'resolver/quux'); + + resolve('./foo', { basedir: dir, 'package': { main: 'quux' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo/index.js')); + t.equal(pkg.main, 'quux'); + }); +}); + +test('normalize', function (t) { + t.plan(2); + var dir = path.join(__dirname, 'resolver/biz/node_modules/grux'); + + resolve('../grux', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'index.js')); + t.equal(pkg, undefined); + }); +}); + +test('cup', function (t) { + t.plan(5); + var dir = path.join(__dirname, 'resolver'); + + resolve('./cup', { basedir: dir, extensions: ['.js', '.coffee'] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'cup.coffee')); + }); + + resolve('./cup.coffee', { basedir: dir }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'cup.coffee')); + }); + + resolve('./cup', { basedir: dir, extensions: ['.js'] }, function (err, res) { + t.equal(err.message, "Cannot find module './cup' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + // Test that filename is reported as the "from" value when passed. + resolve('./cup', { basedir: dir, extensions: ['.js'], filename: path.join(dir, 'cupboard.js') }, function (err, res) { + t.equal(err.message, "Cannot find module './cup' from '" + path.join(dir, 'cupboard.js') + "'"); + }); +}); + +test('mug', function (t) { + t.plan(3); + var dir = path.join(__dirname, 'resolver'); + + resolve('./mug', { basedir: dir }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'mug.js')); + }); + + resolve('./mug', { basedir: dir, extensions: ['.coffee', '.js'] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, '/mug.coffee')); + }); + + resolve('./mug', { basedir: dir, extensions: ['.js', '.coffee'] }, function (err, res) { + t.equal(res, path.join(dir, '/mug.js')); + }); +}); + +test('other path', function (t) { + t.plan(6); + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'bar'); + var otherDir = path.join(resolverDir, 'other_path'); + + resolve('root', { basedir: dir, paths: [otherDir] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(resolverDir, 'other_path/root.js')); + }); + + resolve('lib/other-lib', { basedir: dir, paths: [otherDir] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(resolverDir, 'other_path/lib/other-lib.js')); + }); + + resolve('root', { basedir: dir }, function (err, res) { + t.equal(err.message, "Cannot find module 'root' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + resolve('zzz', { basedir: dir, paths: [otherDir] }, function (err, res) { + t.equal(err.message, "Cannot find module 'zzz' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); +}); + +test('path iterator', function (t) { + t.plan(2); + + var resolverDir = path.join(__dirname, 'resolver'); + + var exactIterator = function (x, start, getPackageCandidates, opts) { + return [path.join(resolverDir, x)]; + }; + + resolve('baz', { packageIterator: exactIterator }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(resolverDir, 'baz/quux.js')); + t.equal(pkg && pkg.name, 'baz'); + }); +}); + +test('empty main', function (t) { + t.plan(1); + + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'empty_main'); + + resolve('./empty_main', { basedir: resolverDir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'index.js')); + }); +}); + +test('incorrect main', function (t) { + t.plan(1); + + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'incorrect_main'); + + resolve('./incorrect_main', { basedir: resolverDir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'index.js')); + }); +}); + +test('missing index', function (t) { + t.plan(2); + + var resolverDir = path.join(__dirname, 'resolver'); + resolve('./missing_index', { basedir: resolverDir }, function (err, res, pkg) { + t.ok(err instanceof Error); + t.equal(err && err.code, 'INCORRECT_PACKAGE_MAIN', 'error has correct error code'); + }); +}); + +test('missing main', function (t) { + t.plan(1); + + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'missing_main'); + + resolve('./missing_main', { basedir: resolverDir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'index.js')); + }); +}); + +test('null main', function (t) { + t.plan(1); + + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'null_main'); + + resolve('./null_main', { basedir: resolverDir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'index.js')); + }); +}); + +test('main: false', function (t) { + t.plan(2); + + var basedir = path.join(__dirname, 'resolver'); + var dir = path.join(basedir, 'false_main'); + resolve('./false_main', { basedir: basedir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal( + res, + path.join(dir, 'index.js'), + '`"main": false`: resolves to `index.js`' + ); + t.deepEqual(pkg, { + name: 'false_main', + main: false + }); + }); +}); + +test('without basedir', function (t) { + t.plan(1); + + var dir = path.join(__dirname, 'resolver/without_basedir'); + var tester = require(path.join(dir, 'main.js')); // eslint-disable-line global-require + + tester(t, function (err, res, pkg) { + if (err) { + t.fail(err); + } else { + t.equal(res, path.join(dir, 'node_modules/mymodule.js')); + } + }); +}); + +test('#52 - incorrectly resolves module-paths like "./someFolder/" when there is a file of the same name', function (t) { + t.plan(2); + + var dir = path.join(__dirname, 'resolver'); + + resolve('./foo', { basedir: path.join(dir, 'same_names') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo.js')); + }); + + resolve('./foo/', { basedir: path.join(dir, 'same_names') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo/index.js')); + }); +}); + +test('#211 - incorrectly resolves module-paths like "." when from inside a folder with a sibling file of the same name', function (t) { + t.plan(2); + + var dir = path.join(__dirname, 'resolver'); + + resolve('./', { basedir: path.join(dir, 'same_names/foo') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo/index.js')); + }); + + resolve('.', { basedir: path.join(dir, 'same_names/foo') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo/index.js')); + }); +}); + +test('async: #121 - treating an existing file as a dir when no basedir', function (t) { + var testFile = path.basename(__filename); + + t.test('sanity check', function (st) { + st.plan(1); + resolve('./' + testFile, function (err, res, pkg) { + if (err) t.fail(err); + st.equal(res, __filename, 'sanity check'); + }); + }); + + t.test('with a fake directory', function (st) { + st.plan(4); + + resolve('./' + testFile + '/blah', function (err, res, pkg) { + st.ok(err, 'there is an error'); + st.notOk(res, 'no result'); + + st.equal(err && err.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve'); + st.equal( + err && err.message, + 'Cannot find module \'./' + testFile + '/blah\' from \'' + __dirname + '\'', + 'can not find nonexistent module' + ); + st.end(); + }); + }); + + t.end(); +}); + +test('async dot main', function (t) { + var start = new Date(); + t.plan(3); + resolve('./resolver/dot_main', function (err, ret) { + t.notOk(err); + t.equal(ret, path.join(__dirname, 'resolver/dot_main/index.js')); + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + t.end(); + }); +}); + +test('async dot slash main', function (t) { + var start = new Date(); + t.plan(3); + resolve('./resolver/dot_slash_main', function (err, ret) { + t.notOk(err); + t.equal(ret, path.join(__dirname, 'resolver/dot_slash_main/index.js')); + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + t.end(); + }); +}); + +test('not a directory', function (t) { + t.plan(6); + var path = './foo'; + resolve(path, { basedir: __filename }, function (err, res, pkg) { + t.ok(err, 'a non-directory errors'); + t.equal(arguments.length, 1); + t.equal(res, undefined); + t.equal(pkg, undefined); + + t.equal(err && err.message, 'Provided basedir "' + __filename + '" is not a directory, or a symlink to a directory'); + t.equal(err && err.code, 'INVALID_BASEDIR'); + }); +}); + +test('non-string "main" field in package.json', function (t) { + t.plan(5); + + var dir = path.join(__dirname, 'resolver'); + resolve('./invalid_main', { basedir: dir }, function (err, res, pkg) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid_main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + t.equal(res, undefined, 'res is undefined'); + t.equal(pkg, undefined, 'pkg is undefined'); + }); +}); + +test('non-string "main" field in package.json', function (t) { + t.plan(5); + + var dir = path.join(__dirname, 'resolver'); + resolve('./invalid_main', { basedir: dir }, function (err, res, pkg) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid_main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + t.equal(res, undefined, 'res is undefined'); + t.equal(pkg, undefined, 'pkg is undefined'); + }); +}); + +test('browser field in package.json', function (t) { + t.plan(3); + + var dir = path.join(__dirname, 'resolver'); + resolve( + './browser_field', + { + basedir: dir, + packageFilter: function packageFilter(pkg) { + if (pkg.browser) { + pkg.main = pkg.browser; // eslint-disable-line no-param-reassign + delete pkg.browser; // eslint-disable-line no-param-reassign + } + return pkg; + } + }, + function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'browser_field', 'b.js')); + t.equal(pkg && pkg.main, 'b'); + t.equal(pkg && pkg.browser, undefined); + } + ); +}); + +test('absolute paths', function (t) { + t.plan(4); + + var extensionless = __filename.slice(0, -path.extname(__filename).length); + + resolve(__filename, function (err, res) { + t.equal( + res, + __filename, + 'absolute path to this file resolves' + ); + }); + resolve(extensionless, function (err, res) { + t.equal( + res, + __filename, + 'extensionless absolute path to this file resolves' + ); + }); + resolve(__filename, { basedir: process.cwd() }, function (err, res) { + t.equal( + res, + __filename, + 'absolute path to this file with a basedir resolves' + ); + }); + resolve(extensionless, { basedir: process.cwd() }, function (err, res) { + t.equal( + res, + __filename, + 'extensionless absolute path to this file with a basedir resolves' + ); + }); +}); + +var malformedDir = path.join(__dirname, 'resolver/malformed_package_json'); +test('malformed package.json', { skip: !fs.existsSync(malformedDir) }, function (t) { + /* eslint operator-linebreak: ["error", "before"], function-paren-newline: "off" */ + t.plan( + (3 * 3) // 3 sets of 3 assertions in the final callback + + 2 // 1 readPackage call with malformed package.json + ); + + var basedir = malformedDir; + var expected = path.join(basedir, 'index.js'); + + resolve('./index.js', { basedir: basedir }, function (err, res, pkg) { + t.error(err, 'no error'); + t.equal(res, expected, 'malformed package.json is silently ignored'); + t.equal(pkg, undefined, 'malformed package.json gives an undefined `pkg` argument'); + }); + + resolve( + './index.js', + { + basedir: basedir, + packageFilter: function (pkg, pkgfile, dir) { + t.fail('should not reach here'); + } + }, + function (err, res, pkg) { + t.error(err, 'with packageFilter: no error'); + t.equal(res, expected, 'with packageFilter: malformed package.json is silently ignored'); + t.equal(pkg, undefined, 'with packageFilter: malformed package.json gives an undefined `pkg` argument'); + } + ); + + resolve( + './index.js', + { + basedir: basedir, + readPackage: function (readFile, pkgfile, cb) { + t.equal(pkgfile, path.join(basedir, 'package.json'), 'readPackageSync: `pkgfile` is package.json path'); + readFile(pkgfile, function (err, result) { + try { + cb(null, JSON.parse(result)); + } catch (e) { + t.ok(e instanceof SyntaxError, 'readPackage: malformed package.json parses as a syntax error'); + cb(e); + } + }); + } + }, + function (err, res, pkg) { + t.error(err, 'with readPackage: no error'); + t.equal(res, expected, 'with readPackage: malformed package.json is silently ignored'); + t.equal(pkg, undefined, 'with readPackage: malformed package.json gives an undefined `pkg` argument'); + } + ); +}); diff --git a/node_modules/eslint-plugin-react/node_modules/resolve/test/resolver/symlinked/package/package.json b/node_modules/eslint-plugin-react/node_modules/resolve/test/resolver/symlinked/package/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8e1b585914a7b46cd21d5d8709ac08bc1fe84962 --- /dev/null +++ b/node_modules/eslint-plugin-react/node_modules/resolve/test/resolver/symlinked/package/package.json @@ -0,0 +1,3 @@ +{ + "main": "bar.js" +} \ No newline at end of file diff --git a/node_modules/eslint-plugin-react/node_modules/resolve/test/resolver/without_basedir/main.js b/node_modules/eslint-plugin-react/node_modules/resolve/test/resolver/without_basedir/main.js new file mode 100644 index 0000000000000000000000000000000000000000..5b31975be69da5efea03fac676afa5f2199831be --- /dev/null +++ b/node_modules/eslint-plugin-react/node_modules/resolve/test/resolver/without_basedir/main.js @@ -0,0 +1,5 @@ +var resolve = require('../../../'); + +module.exports = function (t, cb) { + resolve('mymodule', null, cb); +}; diff --git a/node_modules/eslint-plugin-react/node_modules/resolve/test/resolver_sync.js b/node_modules/eslint-plugin-react/node_modules/resolve/test/resolver_sync.js new file mode 100644 index 0000000000000000000000000000000000000000..1a9fe9d0eebdbfae5aad8ef196cd6d2f98f2a90e --- /dev/null +++ b/node_modules/eslint-plugin-react/node_modules/resolve/test/resolver_sync.js @@ -0,0 +1,727 @@ +var path = require('path'); +var fs = require('fs'); +var test = require('tape'); + +var resolve = require('../'); +var sync = require('../sync'); + +var requireResolveSupportsPaths = require.resolve.length > 1 + && !(/^v12\.[012]\./).test(process.version); // broken in v12.0-12.2, see https://github.com/nodejs/node/issues/27794 + +var requireResolveDefaultPathsBroken = (/^v8\.9\.|^v9\.[01]\.0|^v9\.2\./).test(process.version); +// broken in node v8.9.x, v9.0, v9.1, v9.2.x. see https://github.com/nodejs/node/pull/17113 + +test('`./sync` entry point', function (t) { + t.equal(resolve.sync, sync, '`./sync` entry point is the same as `.sync` on `main`'); + t.end(); +}); + +test('foo', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./foo', { basedir: dir }), + path.join(dir, 'foo.js'), + './foo' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./foo', { basedir: dir }), + require.resolve('./foo', { paths: [dir] }), + './foo: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('./foo.js', { basedir: dir }), + path.join(dir, 'foo.js'), + './foo.js' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./foo.js', { basedir: dir }), + require.resolve('./foo.js', { paths: [dir] }), + './foo.js: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('./foo.js', { basedir: dir, filename: path.join(dir, 'bar.js') }), + path.join(dir, 'foo.js') + ); + + t.throws(function () { + resolve.sync('foo', { basedir: dir }); + }); + + // Test that filename is reported as the "from" value when passed. + t.throws( + function () { + resolve.sync('foo', { basedir: dir, filename: path.join(dir, 'bar.js') }); + }, + { + name: 'Error', + message: "Cannot find module 'foo' from '" + path.join(dir, 'bar.js') + "'" + } + ); + + t.end(); +}); + +test('bar', function (t) { + var dir = path.join(__dirname, 'resolver'); + + var basedir = path.join(dir, 'bar'); + + t.equal( + resolve.sync('foo', { basedir: basedir }), + path.join(dir, 'bar/node_modules/foo/index.js'), + 'foo in bar' + ); + if (!requireResolveDefaultPathsBroken && requireResolveSupportsPaths) { + t.equal( + resolve.sync('foo', { basedir: basedir }), + require.resolve('foo', { paths: [basedir] }), + 'foo in bar: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('baz', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./baz', { basedir: dir }), + path.join(dir, 'baz/quux.js'), + './baz' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./baz', { basedir: dir }), + require.resolve('./baz', { paths: [dir] }), + './baz: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('biz', function (t) { + var dir = path.join(__dirname, 'resolver/biz/node_modules'); + + t.equal( + resolve.sync('./grux', { basedir: dir }), + path.join(dir, 'grux/index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./grux', { basedir: dir }), + require.resolve('./grux', { paths: [dir] }), + './grux: resolve.sync === require.resolve' + ); + } + + var tivDir = path.join(dir, 'grux'); + t.equal( + resolve.sync('tiv', { basedir: tivDir }), + path.join(dir, 'tiv/index.js') + ); + if (!requireResolveDefaultPathsBroken && requireResolveSupportsPaths) { + t.equal( + resolve.sync('tiv', { basedir: tivDir }), + require.resolve('tiv', { paths: [tivDir] }), + 'tiv: resolve.sync === require.resolve' + ); + } + + var gruxDir = path.join(dir, 'tiv'); + t.equal( + resolve.sync('grux', { basedir: gruxDir }), + path.join(dir, 'grux/index.js') + ); + if (!requireResolveDefaultPathsBroken && requireResolveSupportsPaths) { + t.equal( + resolve.sync('grux', { basedir: gruxDir }), + require.resolve('grux', { paths: [gruxDir] }), + 'grux: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('normalize', function (t) { + var dir = path.join(__dirname, 'resolver/biz/node_modules/grux'); + + t.equal( + resolve.sync('../grux', { basedir: dir }), + path.join(dir, 'index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('../grux', { basedir: dir }), + require.resolve('../grux', { paths: [dir] }), + '../grux: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('cup', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./cup', { + basedir: dir, + extensions: ['.js', '.coffee'] + }), + path.join(dir, 'cup.coffee'), + './cup -> ./cup.coffee' + ); + + t.equal( + resolve.sync('./cup.coffee', { basedir: dir }), + path.join(dir, 'cup.coffee'), + './cup.coffee' + ); + + t.throws(function () { + resolve.sync('./cup', { + basedir: dir, + extensions: ['.js'] + }); + }); + + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./cup.coffee', { basedir: dir, extensions: ['.js', '.coffee'] }), + require.resolve('./cup.coffee', { paths: [dir] }), + './cup.coffee: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('mug', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./mug', { basedir: dir }), + path.join(dir, 'mug.js'), + './mug -> ./mug.js' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./mug', { basedir: dir }), + require.resolve('./mug', { paths: [dir] }), + './mug: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('./mug', { + basedir: dir, + extensions: ['.coffee', '.js'] + }), + path.join(dir, 'mug.coffee'), + './mug -> ./mug.coffee' + ); + + t.equal( + resolve.sync('./mug', { + basedir: dir, + extensions: ['.js', '.coffee'] + }), + path.join(dir, 'mug.js'), + './mug -> ./mug.js' + ); + + t.end(); +}); + +test('other path', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'bar'); + var otherDir = path.join(resolverDir, 'other_path'); + + t.equal( + resolve.sync('root', { + basedir: dir, + paths: [otherDir] + }), + path.join(resolverDir, 'other_path/root.js') + ); + + t.equal( + resolve.sync('lib/other-lib', { + basedir: dir, + paths: [otherDir] + }), + path.join(resolverDir, 'other_path/lib/other-lib.js') + ); + + t.throws(function () { + resolve.sync('root', { basedir: dir }); + }); + + t.throws(function () { + resolve.sync('zzz', { + basedir: dir, + paths: [otherDir] + }); + }); + + t.end(); +}); + +test('path iterator', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + + var exactIterator = function (x, start, getPackageCandidates, opts) { + return [path.join(resolverDir, x)]; + }; + + t.equal( + resolve.sync('baz', { packageIterator: exactIterator }), + path.join(resolverDir, 'baz/quux.js') + ); + + t.end(); +}); + +test('incorrect main', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'incorrect_main'); + + t.equal( + resolve.sync('./incorrect_main', { basedir: resolverDir }), + path.join(dir, 'index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./incorrect_main', { basedir: resolverDir }), + require.resolve('./incorrect_main', { paths: [resolverDir] }), + './incorrect_main: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('missing index', function (t) { + t.plan(requireResolveSupportsPaths ? 2 : 1); + + var resolverDir = path.join(__dirname, 'resolver'); + try { + resolve.sync('./missing_index', { basedir: resolverDir }); + t.fail('did not fail'); + } catch (err) { + t.equal(err && err.code, 'INCORRECT_PACKAGE_MAIN', 'error has correct error code'); + } + if (requireResolveSupportsPaths) { + try { + require.resolve('./missing_index', { basedir: resolverDir }); + t.fail('require.resolve did not fail'); + } catch (err) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + } + } +}); + +test('missing main', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'missing_main'); + + t.equal( + resolve.sync('./missing_main', { basedir: resolverDir }), + path.join(dir, 'index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./missing_main', { basedir: resolverDir }), + require.resolve('./missing_main', { paths: [resolverDir] }), + '"main" missing: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('null main', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'null_main'); + + t.equal( + resolve.sync('./null_main', { basedir: resolverDir }), + path.join(dir, 'index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./null_main', { basedir: resolverDir }), + require.resolve('./null_main', { paths: [resolverDir] }), + '`"main": null`: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('main: false', function (t) { + var basedir = path.join(__dirname, 'resolver'); + var dir = path.join(basedir, 'false_main'); + t.equal( + resolve.sync('./false_main', { basedir: basedir }), + path.join(dir, 'index.js'), + '`"main": false`: resolves to `index.js`' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./false_main', { basedir: basedir }), + require.resolve('./false_main', { paths: [basedir] }), + '`"main": false`: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +var stubStatSync = function stubStatSync(fn) { + var statSync = fs.statSync; + try { + fs.statSync = function () { + throw new EvalError('Unknown Error'); + }; + return fn(); + } finally { + fs.statSync = statSync; + } +}; + +test('#79 - re-throw non ENOENT errors from stat', function (t) { + var dir = path.join(__dirname, 'resolver'); + + stubStatSync(function () { + t.throws(function () { + resolve.sync('foo', { basedir: dir }); + }, /Unknown Error/); + }); + + t.end(); +}); + +test('#52 - incorrectly resolves module-paths like "./someFolder/" when there is a file of the same name', function (t) { + var dir = path.join(__dirname, 'resolver'); + var basedir = path.join(dir, 'same_names'); + + t.equal( + resolve.sync('./foo', { basedir: basedir }), + path.join(dir, 'same_names/foo.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./foo', { basedir: basedir }), + require.resolve('./foo', { paths: [basedir] }), + './foo: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('./foo/', { basedir: basedir }), + path.join(dir, 'same_names/foo/index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./foo/', { basedir: basedir }), + require.resolve('./foo/', { paths: [basedir] }), + './foo/: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('#211 - incorrectly resolves module-paths like "." when from inside a folder with a sibling file of the same name', function (t) { + var dir = path.join(__dirname, 'resolver'); + var basedir = path.join(dir, 'same_names/foo'); + + t.equal( + resolve.sync('./', { basedir: basedir }), + path.join(dir, 'same_names/foo/index.js'), + './' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./', { basedir: basedir }), + require.resolve('./', { paths: [basedir] }), + './: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('.', { basedir: basedir }), + path.join(dir, 'same_names/foo/index.js'), + '.' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('.', { basedir: basedir }), + require.resolve('.', { paths: [basedir] }), + '.: resolve.sync === require.resolve', + { todo: true } + ); + } + + t.end(); +}); + +test('sync: #121 - treating an existing file as a dir when no basedir', function (t) { + var testFile = path.basename(__filename); + + t.test('sanity check', function (st) { + st.equal( + resolve.sync('./' + testFile), + __filename, + 'sanity check' + ); + st.equal( + resolve.sync('./' + testFile), + require.resolve('./' + testFile), + 'sanity check: resolve.sync === require.resolve' + ); + + st.end(); + }); + + t.test('with a fake directory', function (st) { + function run() { return resolve.sync('./' + testFile + '/blah'); } + + st.throws(run, 'throws an error'); + + try { + run(); + } catch (e) { + st.equal(e.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve'); + st.equal( + e.message, + 'Cannot find module \'./' + testFile + '/blah\' from \'' + __dirname + '\'', + 'can not find nonexistent module' + ); + } + + st.end(); + }); + + t.end(); +}); + +test('sync dot main', function (t) { + var start = new Date(); + + t.equal( + resolve.sync('./resolver/dot_main'), + path.join(__dirname, 'resolver/dot_main/index.js'), + './resolver/dot_main' + ); + t.equal( + resolve.sync('./resolver/dot_main'), + require.resolve('./resolver/dot_main'), + './resolver/dot_main: resolve.sync === require.resolve' + ); + + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + + t.end(); +}); + +test('sync dot slash main', function (t) { + var start = new Date(); + + t.equal( + resolve.sync('./resolver/dot_slash_main'), + path.join(__dirname, 'resolver/dot_slash_main/index.js') + ); + t.equal( + resolve.sync('./resolver/dot_slash_main'), + require.resolve('./resolver/dot_slash_main'), + './resolver/dot_slash_main: resolve.sync === require.resolve' + ); + + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + + t.end(); +}); + +test('not a directory', function (t) { + var path = './foo'; + try { + resolve.sync(path, { basedir: __filename }); + t.fail(); + } catch (err) { + t.ok(err, 'a non-directory errors'); + t.equal(err && err.message, 'Provided basedir "' + __filename + '" is not a directory, or a symlink to a directory'); + t.equal(err && err.code, 'INVALID_BASEDIR'); + } + t.end(); +}); + +test('non-string "main" field in package.json', function (t) { + var dir = path.join(__dirname, 'resolver'); + try { + var result = resolve.sync('./invalid_main', { basedir: dir }); + t.equal(result, undefined, 'result should not exist'); + t.fail('should not get here'); + } catch (err) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid_main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + } + t.end(); +}); + +test('non-string "main" field in package.json', function (t) { + var dir = path.join(__dirname, 'resolver'); + try { + var result = resolve.sync('./invalid_main', { basedir: dir }); + t.equal(result, undefined, 'result should not exist'); + t.fail('should not get here'); + } catch (err) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid_main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + } + t.end(); +}); + +test('browser field in package.json', function (t) { + var dir = path.join(__dirname, 'resolver'); + var res = resolve.sync('./browser_field', { + basedir: dir, + packageFilter: function packageFilter(pkg) { + if (pkg.browser) { + pkg.main = pkg.browser; // eslint-disable-line no-param-reassign + delete pkg.browser; // eslint-disable-line no-param-reassign + } + return pkg; + } + }); + t.equal(res, path.join(dir, 'browser_field', 'b.js')); + t.end(); +}); + +test('absolute paths', function (t) { + var extensionless = __filename.slice(0, -path.extname(__filename).length); + + t.equal( + resolve.sync(__filename), + __filename, + 'absolute path to this file resolves' + ); + t.equal( + resolve.sync(__filename), + require.resolve(__filename), + 'absolute path to this file: resolve.sync === require.resolve' + ); + + t.equal( + resolve.sync(extensionless), + __filename, + 'extensionless absolute path to this file resolves' + ); + t.equal( + resolve.sync(__filename), + require.resolve(__filename), + 'absolute path to this file: resolve.sync === require.resolve' + ); + + t.equal( + resolve.sync(__filename, { basedir: process.cwd() }), + __filename, + 'absolute path to this file with a basedir resolves' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync(__filename, { basedir: process.cwd() }), + require.resolve(__filename, { paths: [process.cwd()] }), + 'absolute path to this file + basedir: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync(extensionless, { basedir: process.cwd() }), + __filename, + 'extensionless absolute path to this file with a basedir resolves' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync(extensionless, { basedir: process.cwd() }), + require.resolve(extensionless, { paths: [process.cwd()] }), + 'extensionless absolute path to this file + basedir: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +var malformedDir = path.join(__dirname, 'resolver/malformed_package_json'); +test('malformed package.json', { skip: !fs.existsSync(malformedDir) }, function (t) { + t.plan(5 + (requireResolveSupportsPaths ? 1 : 0)); + + var basedir = malformedDir; + var expected = path.join(basedir, 'index.js'); + + t.equal( + resolve.sync('./index.js', { basedir: basedir }), + expected, + 'malformed package.json is silently ignored' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./index.js', { basedir: basedir }), + require.resolve('./index.js', { paths: [basedir] }), + 'malformed package.json: resolve.sync === require.resolve' + ); + } + + var res1 = resolve.sync( + './index.js', + { + basedir: basedir, + packageFilter: function (pkg, pkgfile, dir) { + t.fail('should not reach here'); + } + } + ); + + t.equal( + res1, + expected, + 'with packageFilter: malformed package.json is silently ignored' + ); + + var res2 = resolve.sync( + './index.js', + { + basedir: basedir, + readPackageSync: function (readFileSync, pkgfile) { + t.equal(pkgfile, path.join(basedir, 'package.json'), 'readPackageSync: `pkgfile` is package.json path'); + var result = String(readFileSync(pkgfile)); + try { + return JSON.parse(result); + } catch (e) { + t.ok(e instanceof SyntaxError, 'readPackageSync: malformed package.json parses as a syntax error'); + throw e; + } + } + } + ); + + t.equal( + res2, + expected, + 'with readPackageSync: malformed package.json is silently ignored' + ); +}); diff --git a/node_modules/eslint-plugin-react/node_modules/resolve/test/shadowed_core.js b/node_modules/eslint-plugin-react/node_modules/resolve/test/shadowed_core.js new file mode 100644 index 0000000000000000000000000000000000000000..3a5f4fcff728f305c2d3d17a416fea4cbfe31f6b --- /dev/null +++ b/node_modules/eslint-plugin-react/node_modules/resolve/test/shadowed_core.js @@ -0,0 +1,54 @@ +var test = require('tape'); +var resolve = require('../'); +var path = require('path'); + +test('shadowed core modules still return core module', function (t) { + t.plan(2); + + resolve('util', { basedir: path.join(__dirname, 'shadowed_core') }, function (err, res) { + t.ifError(err); + t.equal(res, 'util'); + }); +}); + +test('shadowed core modules still return core module [sync]', function (t) { + t.plan(1); + + var res = resolve.sync('util', { basedir: path.join(__dirname, 'shadowed_core') }); + + t.equal(res, 'util'); +}); + +test('shadowed core modules return shadow when appending `/`', function (t) { + t.plan(2); + + resolve('util/', { basedir: path.join(__dirname, 'shadowed_core') }, function (err, res) { + t.ifError(err); + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); + }); +}); + +test('shadowed core modules return shadow when appending `/` [sync]', function (t) { + t.plan(1); + + var res = resolve.sync('util/', { basedir: path.join(__dirname, 'shadowed_core') }); + + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); +}); + +test('shadowed core modules return shadow with `includeCoreModules: false`', function (t) { + t.plan(2); + + resolve('util', { basedir: path.join(__dirname, 'shadowed_core'), includeCoreModules: false }, function (err, res) { + t.ifError(err); + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); + }); +}); + +test('shadowed core modules return shadow with `includeCoreModules: false` [sync]', function (t) { + t.plan(1); + + var res = resolve.sync('util', { basedir: path.join(__dirname, 'shadowed_core'), includeCoreModules: false }); + + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); +}); diff --git a/node_modules/eslint-plugin-react/node_modules/resolve/test/shadowed_core/node_modules/util/index.js b/node_modules/eslint-plugin-react/node_modules/resolve/test/shadowed_core/node_modules/util/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/eslint-plugin-react/node_modules/resolve/test/subdirs.js b/node_modules/eslint-plugin-react/node_modules/resolve/test/subdirs.js new file mode 100644 index 0000000000000000000000000000000000000000..b7b8450a9ef231940eca37b8fe951310147a9470 --- /dev/null +++ b/node_modules/eslint-plugin-react/node_modules/resolve/test/subdirs.js @@ -0,0 +1,13 @@ +var test = require('tape'); +var resolve = require('../'); +var path = require('path'); + +test('subdirs', function (t) { + t.plan(2); + + var dir = path.join(__dirname, '/subdirs'); + resolve('a/b/c/x.json', { basedir: dir }, function (err, res) { + t.ifError(err); + t.equal(res, path.join(dir, 'node_modules/a/b/c/x.json')); + }); +}); diff --git a/node_modules/eslint-plugin-react/node_modules/resolve/test/symlinks.js b/node_modules/eslint-plugin-react/node_modules/resolve/test/symlinks.js new file mode 100644 index 0000000000000000000000000000000000000000..2f1f279677bd2dba2f072446b8529d4ab20293ee --- /dev/null +++ b/node_modules/eslint-plugin-react/node_modules/resolve/test/symlinks.js @@ -0,0 +1,175 @@ +var path = require('path'); +var fs = require('fs'); +var test = require('tape'); +var map = require('array.prototype.map'); +var resolve = require('../'); + +var symlinkDir = path.join(__dirname, 'resolver', 'symlinked', 'symlink'); +var packageDir = path.join(__dirname, 'resolver', 'symlinked', '_', 'node_modules', 'package'); +var modADir = path.join(__dirname, 'symlinks', 'source', 'node_modules', 'mod-a'); +var symlinkModADir = path.join(__dirname, 'symlinks', 'dest', 'node_modules', 'mod-a'); +try { + fs.unlinkSync(symlinkDir); +} catch (err) {} +try { + fs.unlinkSync(packageDir); +} catch (err) {} +try { + fs.unlinkSync(modADir); +} catch (err) {} +try { + fs.unlinkSync(symlinkModADir); +} catch (err) {} + +try { + fs.symlinkSync('./_/symlink_target', symlinkDir, 'dir'); +} catch (err) { + if (err.code !== 'EEXIST') { + // if fails then it is probably on Windows and lets try to create a junction + fs.symlinkSync(path.join(__dirname, 'resolver', 'symlinked', '_', 'symlink_target') + '\\', symlinkDir, 'junction'); + } +} +try { + fs.symlinkSync('../../package', packageDir, 'dir'); +} catch (err) { + // if fails then it is probably on Windows and lets try to create a junction + fs.symlinkSync(path.join(__dirname, '..', '..', 'package') + '\\', packageDir, 'junction'); +} +try { + fs.symlinkSync('../../source/node_modules/mod-a', symlinkModADir, 'dir'); +} catch (err) { + // if fails then it is probably on Windows and lets try to create a junction + fs.symlinkSync(path.join(__dirname, '..', '..', 'source', 'node_modules', 'mod-a') + '\\', symlinkModADir, 'junction'); +} + +test('symlink', function (t) { + t.plan(2); + + resolve('foo', { basedir: symlinkDir }, function (err, res, pkg) { + t.error(err); + t.equal(res, path.join(__dirname, 'resolver', 'symlinked', '_', 'node_modules', 'foo.js')); + }); +}); + +test('sync symlink when preserveSymlinks = true', function (t) { + t.plan(4); + + resolve('foo', { basedir: symlinkDir, preserveSymlinks: true }, function (err, res, pkg) { + t.ok(err, 'there is an error'); + t.notOk(res, 'no result'); + + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve'); + t.equal( + err && err.message, + 'Cannot find module \'foo\' from \'' + symlinkDir + '\'', + 'can not find nonexistent module' + ); + }); +}); + +test('sync symlink', function (t) { + var start = new Date(); + t.doesNotThrow(function () { + t.equal( + resolve.sync('foo', { basedir: symlinkDir, preserveSymlinks: false }), + path.join(__dirname, 'resolver', 'symlinked', '_', 'node_modules', 'foo.js') + ); + }); + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + t.end(); +}); + +test('sync symlink when preserveSymlinks = true', function (t) { + t.throws(function () { + resolve.sync('foo', { basedir: symlinkDir, preserveSymlinks: true }); + }, /Cannot find module 'foo'/); + t.end(); +}); + +test('sync symlink from node_modules to other dir when preserveSymlinks = false', function (t) { + var basedir = path.join(__dirname, 'resolver', 'symlinked', '_'); + var fn = resolve.sync('package', { basedir: basedir, preserveSymlinks: false }); + + t.equal(fn, path.resolve(__dirname, 'resolver/symlinked/package/bar.js')); + t.end(); +}); + +test('async symlink from node_modules to other dir when preserveSymlinks = false', function (t) { + t.plan(2); + var basedir = path.join(__dirname, 'resolver', 'symlinked', '_'); + resolve('package', { basedir: basedir, preserveSymlinks: false }, function (err, result) { + t.notOk(err, 'no error'); + t.equal(result, path.resolve(__dirname, 'resolver/symlinked/package/bar.js')); + }); +}); + +test('packageFilter', function (t) { + function relative(x) { + return path.relative(__dirname, x); + } + + function testPackageFilter(preserveSymlinks) { + return function (st) { + st.plan(5); + + var destMain = 'symlinks/dest/node_modules/mod-a/index.js'; + var destPkg = 'symlinks/dest/node_modules/mod-a/package.json'; + var sourceMain = 'symlinks/source/node_modules/mod-a/index.js'; + var sourcePkg = 'symlinks/source/node_modules/mod-a/package.json'; + var destDir = path.join(__dirname, 'symlinks', 'dest'); + + var packageFilterPath = []; + var actualPath = resolve.sync('mod-a', { + basedir: destDir, + preserveSymlinks: preserveSymlinks, + packageFilter: function (pkg, pkgfile, dir) { + packageFilterPath.push(pkgfile); + } + }); + st.equal( + relative(actualPath), + path.normalize(preserveSymlinks ? destMain : sourceMain), + 'sync: actual path is correct' + ); + st.deepEqual( + map(packageFilterPath, relative), + map(preserveSymlinks ? [destPkg, destPkg] : [sourcePkg, sourcePkg], path.normalize), + 'sync: packageFilter pkgfile arg is correct' + ); + + var asyncPackageFilterPath = []; + resolve( + 'mod-a', + { + basedir: destDir, + preserveSymlinks: preserveSymlinks, + packageFilter: function (pkg, pkgfile) { + asyncPackageFilterPath.push(pkgfile); + } + }, + function (err, actualPath) { + st.error(err, 'no error'); + st.equal( + relative(actualPath), + path.normalize(preserveSymlinks ? destMain : sourceMain), + 'async: actual path is correct' + ); + st.deepEqual( + map(asyncPackageFilterPath, relative), + map( + preserveSymlinks ? [destPkg, destPkg, destPkg] : [sourcePkg, sourcePkg, sourcePkg], + path.normalize + ), + 'async: packageFilter pkgfile arg is correct' + ); + } + ); + }; + } + + t.test('preserveSymlinks: false', testPackageFilter(false)); + + t.test('preserveSymlinks: true', testPackageFilter(true)); + + t.end(); +}); diff --git a/node_modules/eslint-plugin-react/node_modules/semver/LICENSE b/node_modules/eslint-plugin-react/node_modules/semver/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..19129e315fe593965a2fdd50ec0d1253bcbd2ece --- /dev/null +++ b/node_modules/eslint-plugin-react/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/eslint-plugin-react/node_modules/semver/README.md b/node_modules/eslint-plugin-react/node_modules/semver/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2293a14fdc3579558dbe9fbc50aa549657948c3e --- /dev/null +++ b/node_modules/eslint-plugin-react/node_modules/semver/README.md @@ -0,0 +1,443 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Install + +```bash +npm install semver +```` + +## Usage + +As a node module: + +```js +const semver = require('semver') + +semver.valid('1.2.3') // '1.2.3' +semver.valid('a.b.c') // null +semver.clean(' =v1.2.3 ') // '1.2.3' +semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true +semver.gt('1.2.3', '9.8.7') // false +semver.lt('1.2.3', '9.8.7') // true +semver.minVersion('>=1.0.0') // '1.0.0' +semver.valid(semver.coerce('v2')) // '2.0.0' +semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' +``` + +As a command-line utility: + +``` +$ semver -h + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them. +``` + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. + +## Ranges + +A `version range` is a set of `comparators` which specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional, but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. The +version `3.4.5` *would* satisfy the range, because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose for this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range matching +semantics. + +Second, a user who has opted into using a prerelease version has +clearly indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +Note that this behavior can be suppressed (treating all prerelease +versions as if they were normal versions, for the purpose of range +matching) by setting the `includePrerelease` flag on the options +object to any +[functions](https://github.com/npm/node-semver#functions) that do +range matching. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta') +// '1.2.4-beta.0' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```bash +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any version satisfies) +* `1.x` := `>=1.0.0 <2.0.0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero element in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0` +* `^0.2.3` := `>=0.2.3 <0.3.0` +* `^0.0.3` := `>=0.0.3 <0.0.4` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0` +* `^0.0.x` := `>=0.0.0 <0.1.0` +* `^0.0` := `>=0.0.0 <0.1.0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0` +* `^0.x` := `>=0.0.0 <1.0.0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `options` object argument. All +options in this object are `false` by default. The options supported +are: + +- `loose` Be more forgiving about not-quite-valid semver strings. + (Any resulting output will always be 100% strict compliant, of + course.) For backwards compatibility reasons, if the `options` + argument is a boolean value instead of an object, it is interpreted + to be the `loose` param. +- `includePrerelease` Set to suppress the [default + behavior](https://github.com/npm/node-semver#prerelease-tags) of + excluding prerelease tagged versions from ranges unless they are + explicitly opted into. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, release)`: Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, or `prerelease`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, the `prerelease` will work the + same as `prepatch`. It increments the patch version, then makes a + prerelease. If the input version is already a prerelease it simply + increments it. +* `prerelease(v)`: Returns an array of prerelease components, or null + if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. +* `intersects(r1, r2, loose)`: Return true if the two supplied ranges + or comparators intersect. +* `parse(v)`: Attempt to parse a string as a semantic version, returning either + a `SemVer` object or `null`. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the exact same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions + are equal. Sorts in ascending order if passed to `Array.sort()`. + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `diff(v1, v2)`: Returns difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + +### Comparators + +* `intersects(comparator)`: Return true if the comparators intersect + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `minSatisfying(versions, range)`: Return the lowest version in the list + that satisfies the range, or `null` if none of them do. +* `minVersion(range)`: Return the lowest version that can possibly match + the given range. +* `gtr(version, range)`: Return `true` if version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) +* `intersects(range)`: Return true if any of the ranges comparators intersect + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so the version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. + +### Coercion + +* `coerce(version, options)`: Coerces a string to semver if possible + +This aims to provide a very forgiving translation of a non-semver string to +semver. It looks for the first digit in a string, and consumes all +remaining characters which satisfy at least a partial semver (e.g., `1`, +`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer +versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All +surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes +`3.4.0`). Only text which lacks digits will fail coercion (`version one` +is not valid). The maximum length for any semver component considered for +coercion is 16 characters; longer components will be ignored +(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any +semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value +components are invalid (`9999999999999999.4.7.4` is likely invalid). + +If the `options.rtl` flag is set, then `coerce` will return the right-most +coercible tuple that does not share an ending index with a longer coercible +tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not +`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of +any other overlapping SemVer tuple. + +### Clean + +* `clean(version)`: Clean a string to be a valid semver if possible + +This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges. + +ex. +* `s.clean(' = v 2.1.5foo')`: `null` +* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean(' = v 2.1.5-foo')`: `null` +* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean('=v2.1.5')`: `'2.1.5'` +* `s.clean(' =v2.1.5')`: `2.1.5` +* `s.clean(' 2.1.5 ')`: `'2.1.5'` +* `s.clean('~1.0.0')`: `null` diff --git a/node_modules/eslint-plugin-react/node_modules/semver/bin/semver.js b/node_modules/eslint-plugin-react/node_modules/semver/bin/semver.js new file mode 100644 index 0000000000000000000000000000000000000000..666034a75d8442be9bb2d9c55c3909b55a093cb5 --- /dev/null +++ b/node_modules/eslint-plugin-react/node_modules/semver/bin/semver.js @@ -0,0 +1,174 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +var argv = process.argv.slice(2) + +var versions = [] + +var range = [] + +var inc = null + +var version = require('../package.json').version + +var loose = false + +var includePrerelease = false + +var coerce = false + +var rtl = false + +var identifier + +var semver = require('../semver') + +var reverse = false + +var options = {} + +main() + +function main () { + if (!argv.length) return help() + while (argv.length) { + var a = argv.shift() + var indexOfEqualSign = a.indexOf('=') + if (indexOfEqualSign !== -1) { + a = a.slice(0, indexOfEqualSign) + argv.unshift(a.slice(indexOfEqualSign + 1)) + } + switch (a) { + case '-rv': case '-rev': case '--rev': case '--reverse': + reverse = true + break + case '-l': case '--loose': + loose = true + break + case '-p': case '--include-prerelease': + includePrerelease = true + break + case '-v': case '--version': + versions.push(argv.shift()) + break + case '-i': case '--inc': case '--increment': + switch (argv[0]) { + case 'major': case 'minor': case 'patch': case 'prerelease': + case 'premajor': case 'preminor': case 'prepatch': + inc = argv.shift() + break + default: + inc = 'patch' + break + } + break + case '--preid': + identifier = argv.shift() + break + case '-r': case '--range': + range.push(argv.shift()) + break + case '-c': case '--coerce': + coerce = true + break + case '--rtl': + rtl = true + break + case '--ltr': + rtl = false + break + case '-h': case '--help': case '-?': + return help() + default: + versions.push(a) + break + } + } + + var options = { loose: loose, includePrerelease: includePrerelease, rtl: rtl } + + versions = versions.map(function (v) { + return coerce ? (semver.coerce(v, options) || { version: v }).version : v + }).filter(function (v) { + return semver.valid(v) + }) + if (!versions.length) return fail() + if (inc && (versions.length !== 1 || range.length)) { return failInc() } + + for (var i = 0, l = range.length; i < l; i++) { + versions = versions.filter(function (v) { + return semver.satisfies(v, range[i], options) + }) + if (!versions.length) return fail() + } + return success(versions) +} + +function failInc () { + console.error('--inc can only be used on a single version with no range') + fail() +} + +function fail () { process.exit(1) } + +function success () { + var compare = reverse ? 'rcompare' : 'compare' + versions.sort(function (a, b) { + return semver[compare](a, b, options) + }).map(function (v) { + return semver.clean(v, options) + }).map(function (v) { + return inc ? semver.inc(v, inc, options, identifier) : v + }).forEach(function (v, i, _) { console.log(v) }) +} + +function help () { + console.log(['SemVer ' + version, + '', + 'A JavaScript implementation of the https://semver.org/ specification', + 'Copyright Isaac Z. Schlueter', + '', + 'Usage: semver [options] [ [...]]', + 'Prints valid versions sorted by SemVer precedence', + '', + 'Options:', + '-r --range ', + ' Print versions that match the specified range.', + '', + '-i --increment []', + ' Increment a version by the specified level. Level can', + ' be one of: major, minor, patch, premajor, preminor,', + " prepatch, or prerelease. Default level is 'patch'.", + ' Only one version may be specified.', + '', + '--preid ', + ' Identifier to be used to prefix premajor, preminor,', + ' prepatch or prerelease version increments.', + '', + '-l --loose', + ' Interpret versions and ranges loosely', + '', + '-p --include-prerelease', + ' Always include prerelease versions in range matching', + '', + '-c --coerce', + ' Coerce a string into SemVer if possible', + ' (does not imply --loose)', + '', + '--rtl', + ' Coerce version strings right to left', + '', + '--ltr', + ' Coerce version strings left to right (default)', + '', + 'Program exits successfully if any valid version satisfies', + 'all supplied ranges, and prints all satisfying versions.', + '', + 'If no satisfying versions are found, then exits failure.', + '', + 'Versions are printed in ascending order, so supplying', + 'multiple versions to the utility will just sort them.' + ].join('\n')) +} diff --git a/node_modules/eslint-plugin-react/node_modules/semver/package.json b/node_modules/eslint-plugin-react/node_modules/semver/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6b970a629ffe81d300d6b0469fa9b1992ca24c8e --- /dev/null +++ b/node_modules/eslint-plugin-react/node_modules/semver/package.json @@ -0,0 +1,38 @@ +{ + "name": "semver", + "version": "6.3.1", + "description": "The semantic version parser used by npm.", + "main": "semver.js", + "scripts": { + "test": "tap test/ --100 --timeout=30", + "lint": "echo linting disabled", + "postlint": "template-oss-check", + "template-oss-apply": "template-oss-apply --force", + "lintfix": "npm run lint -- --fix", + "snap": "tap test/ --100 --timeout=30", + "posttest": "npm run lint" + }, + "devDependencies": { + "@npmcli/template-oss": "4.17.0", + "tap": "^12.7.0" + }, + "license": "ISC", + "repository": { + "type": "git", + "url": "https://github.com/npm/node-semver.git" + }, + "bin": { + "semver": "./bin/semver.js" + }, + "files": [ + "bin", + "range.bnf", + "semver.js" + ], + "author": "GitHub Inc.", + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "content": "./scripts/template-oss", + "version": "4.17.0" + } +} diff --git a/node_modules/eslint-plugin-react/node_modules/semver/range.bnf b/node_modules/eslint-plugin-react/node_modules/semver/range.bnf new file mode 100644 index 0000000000000000000000000000000000000000..d4c6ae0d76c9ac0c10c93062e5ff9cec277b07cd --- /dev/null +++ b/node_modules/eslint-plugin-react/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | [1-9] ( [0-9] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/node_modules/eslint-plugin-react/node_modules/semver/semver.js b/node_modules/eslint-plugin-react/node_modules/semver/semver.js new file mode 100644 index 0000000000000000000000000000000000000000..39319c13cac27d65d88d34dac95470a6494a0dae --- /dev/null +++ b/node_modules/eslint-plugin-react/node_modules/semver/semver.js @@ -0,0 +1,1643 @@ +exports = module.exports = SemVer + +var debug +/* istanbul ignore next */ +if (typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG)) { + debug = function () { + var args = Array.prototype.slice.call(arguments, 0) + args.unshift('SEMVER') + console.log.apply(console, args) + } +} else { + debug = function () {} +} + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0' + +var MAX_LENGTH = 256 +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +var MAX_SAFE_COMPONENT_LENGTH = 16 + +var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 + +// The actual regexps go on exports.re +var re = exports.re = [] +var safeRe = exports.safeRe = [] +var src = exports.src = [] +var t = exports.tokens = {} +var R = 0 + +function tok (n) { + t[n] = R++ +} + +var LETTERDASHNUMBER = '[a-zA-Z0-9-]' + +// Replace some greedy regex tokens to prevent regex dos issues. These regex are +// used internally via the safeRe object since all inputs in this library get +// normalized first to trim and collapse all extra whitespace. The original +// regexes are exported for userland consumption and lower level usage. A +// future breaking change could export the safer regex only with a note that +// all input should have extra whitespace removed. +var safeRegexReplacements = [ + ['\\s', 1], + ['\\d', MAX_LENGTH], + [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], +] + +function makeSafeRe (value) { + for (var i = 0; i < safeRegexReplacements.length; i++) { + var token = safeRegexReplacements[i][0] + var max = safeRegexReplacements[i][1] + value = value + .split(token + '*').join(token + '{0,' + max + '}') + .split(token + '+').join(token + '{1,' + max + '}') + } + return value +} + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +tok('NUMERICIDENTIFIER') +src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*' +tok('NUMERICIDENTIFIERLOOSE') +src[t.NUMERICIDENTIFIERLOOSE] = '\\d+' + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +tok('NONNUMERICIDENTIFIER') +src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-]' + LETTERDASHNUMBER + '*' + +// ## Main Version +// Three dot-separated numeric identifiers. + +tok('MAINVERSION') +src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIER] + ')' + +tok('MAINVERSIONLOOSE') +src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')' + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +tok('PRERELEASEIDENTIFIER') +src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] + + '|' + src[t.NONNUMERICIDENTIFIER] + ')' + +tok('PRERELEASEIDENTIFIERLOOSE') +src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] + + '|' + src[t.NONNUMERICIDENTIFIER] + ')' + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +tok('PRERELEASE') +src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] + + '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))' + +tok('PRERELEASELOOSE') +src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))' + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +tok('BUILDIDENTIFIER') +src[t.BUILDIDENTIFIER] = LETTERDASHNUMBER + '+' + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +tok('BUILD') +src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] + + '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))' + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +tok('FULL') +tok('FULLPLAIN') +src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] + + src[t.PRERELEASE] + '?' + + src[t.BUILD] + '?' + +src[t.FULL] = '^' + src[t.FULLPLAIN] + '$' + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +tok('LOOSEPLAIN') +src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] + + src[t.PRERELEASELOOSE] + '?' + + src[t.BUILD] + '?' + +tok('LOOSE') +src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$' + +tok('GTLT') +src[t.GTLT] = '((?:<|>)?=?)' + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +tok('XRANGEIDENTIFIERLOOSE') +src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' +tok('XRANGEIDENTIFIER') +src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*' + +tok('XRANGEPLAIN') +src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + + '(?:' + src[t.PRERELEASE] + ')?' + + src[t.BUILD] + '?' + + ')?)?' + +tok('XRANGEPLAINLOOSE') +src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[t.PRERELEASELOOSE] + ')?' + + src[t.BUILD] + '?' + + ')?)?' + +tok('XRANGE') +src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$' +tok('XRANGELOOSE') +src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$' + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +tok('COERCE') +src[t.COERCE] = '(^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])' +tok('COERCERTL') +re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g') +safeRe[t.COERCERTL] = new RegExp(makeSafeRe(src[t.COERCE]), 'g') + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +tok('LONETILDE') +src[t.LONETILDE] = '(?:~>?)' + +tok('TILDETRIM') +src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+' +re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g') +safeRe[t.TILDETRIM] = new RegExp(makeSafeRe(src[t.TILDETRIM]), 'g') +var tildeTrimReplace = '$1~' + +tok('TILDE') +src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$' +tok('TILDELOOSE') +src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$' + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +tok('LONECARET') +src[t.LONECARET] = '(?:\\^)' + +tok('CARETTRIM') +src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+' +re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g') +safeRe[t.CARETTRIM] = new RegExp(makeSafeRe(src[t.CARETTRIM]), 'g') +var caretTrimReplace = '$1^' + +tok('CARET') +src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$' +tok('CARETLOOSE') +src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$' + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +tok('COMPARATORLOOSE') +src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$' +tok('COMPARATOR') +src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$' + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +tok('COMPARATORTRIM') +src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] + + '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')' + +// this one has to use the /g flag +re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g') +safeRe[t.COMPARATORTRIM] = new RegExp(makeSafeRe(src[t.COMPARATORTRIM]), 'g') +var comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +tok('HYPHENRANGE') +src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[t.XRANGEPLAIN] + ')' + + '\\s*$' + +tok('HYPHENRANGELOOSE') +src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[t.XRANGEPLAINLOOSE] + ')' + + '\\s*$' + +// Star ranges basically just allow anything at all. +tok('STAR') +src[t.STAR] = '(<|>)?=?\\s*\\*' + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]) + if (!re[i]) { + re[i] = new RegExp(src[i]) + + // Replace all greedy whitespace to prevent regex dos issues. These regex are + // used internally via the safeRe object since all inputs in this library get + // normalized first to trim and collapse all extra whitespace. The original + // regexes are exported for userland consumption and lower level usage. A + // future breaking change could export the safer regex only with a note that + // all input should have extra whitespace removed. + safeRe[i] = new RegExp(makeSafeRe(src[i])) + } +} + +exports.parse = parse +function parse (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + var r = options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL] + if (!r.test(version)) { + return null + } + + try { + return new SemVer(version, options) + } catch (er) { + return null + } +} + +exports.valid = valid +function valid (version, options) { + var v = parse(version, options) + return v ? v.version : null +} + +exports.clean = clean +function clean (version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} + +exports.SemVer = SemVer + +function SemVer (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + } + + if (!(this instanceof SemVer)) { + return new SemVer(version, options) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + + var m = version.trim().match(options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL]) + + if (!m) { + throw new TypeError('Invalid Version: ' + version) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map(function (id) { + if (/^[0-9]+$/.test(id)) { + var num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() +} + +SemVer.prototype.format = function () { + this.version = this.major + '.' + this.minor + '.' + this.patch + if (this.prerelease.length) { + this.version += '-' + this.prerelease.join('.') + } + return this.version +} + +SemVer.prototype.toString = function () { + return this.version +} + +SemVer.prototype.compare = function (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return this.compareMain(other) || this.comparePre(other) +} + +SemVer.prototype.compareMain = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) +} + +SemVer.prototype.comparePre = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + var i = 0 + do { + var a = this.prerelease[i] + var b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) +} + +SemVer.prototype.compareBuild = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + var i = 0 + do { + var a = this.build[i] + var b = other.build[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) +} + +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + var i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break + + default: + throw new Error('invalid increment argument: ' + release) + } + this.format() + this.raw = this.version + return this +} + +exports.inc = inc +function inc (version, release, loose, identifier) { + if (typeof (loose) === 'string') { + identifier = loose + loose = undefined + } + + try { + return new SemVer(version, loose).inc(release, identifier).version + } catch (er) { + return null + } +} + +exports.diff = diff +function diff (version1, version2) { + if (eq(version1, version2)) { + return null + } else { + var v1 = parse(version1) + var v2 = parse(version2) + var prefix = '' + if (v1.prerelease.length || v2.prerelease.length) { + prefix = 'pre' + var defaultResult = 'prerelease' + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } +} + +exports.compareIdentifiers = compareIdentifiers + +var numeric = /^[0-9]+$/ +function compareIdentifiers (a, b) { + var anum = numeric.test(a) + var bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +exports.rcompareIdentifiers = rcompareIdentifiers +function rcompareIdentifiers (a, b) { + return compareIdentifiers(b, a) +} + +exports.major = major +function major (a, loose) { + return new SemVer(a, loose).major +} + +exports.minor = minor +function minor (a, loose) { + return new SemVer(a, loose).minor +} + +exports.patch = patch +function patch (a, loose) { + return new SemVer(a, loose).patch +} + +exports.compare = compare +function compare (a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)) +} + +exports.compareLoose = compareLoose +function compareLoose (a, b) { + return compare(a, b, true) +} + +exports.compareBuild = compareBuild +function compareBuild (a, b, loose) { + var versionA = new SemVer(a, loose) + var versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) +} + +exports.rcompare = rcompare +function rcompare (a, b, loose) { + return compare(b, a, loose) +} + +exports.sort = sort +function sort (list, loose) { + return list.sort(function (a, b) { + return exports.compareBuild(a, b, loose) + }) +} + +exports.rsort = rsort +function rsort (list, loose) { + return list.sort(function (a, b) { + return exports.compareBuild(b, a, loose) + }) +} + +exports.gt = gt +function gt (a, b, loose) { + return compare(a, b, loose) > 0 +} + +exports.lt = lt +function lt (a, b, loose) { + return compare(a, b, loose) < 0 +} + +exports.eq = eq +function eq (a, b, loose) { + return compare(a, b, loose) === 0 +} + +exports.neq = neq +function neq (a, b, loose) { + return compare(a, b, loose) !== 0 +} + +exports.gte = gte +function gte (a, b, loose) { + return compare(a, b, loose) >= 0 +} + +exports.lte = lte +function lte (a, b, loose) { + return compare(a, b, loose) <= 0 +} + +exports.cmp = cmp +function cmp (a, op, b, loose) { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError('Invalid operator: ' + op) + } +} + +exports.Comparator = Comparator +function Comparator (comp, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + if (!(this instanceof Comparator)) { + return new Comparator(comp, options) + } + + comp = comp.trim().split(/\s+/).join(' ') + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) +} + +var ANY = {} +Comparator.prototype.parse = function (comp) { + var r = this.options.loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR] + var m = comp.match(r) + + if (!m) { + throw new TypeError('Invalid comparator: ' + comp) + } + + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } +} + +Comparator.prototype.toString = function () { + return this.value +} + +Comparator.prototype.test = function (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY || version === ANY) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) +} + +Comparator.prototype.intersects = function (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + var rangeTmp + + if (this.operator === '') { + if (this.value === '') { + return true + } + rangeTmp = new Range(comp.value, options) + return satisfies(this.value, rangeTmp, options) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + rangeTmp = new Range(this.value, options) + return satisfies(comp.semver, rangeTmp, options) + } + + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + var sameSemVer = this.semver.version === comp.semver.version + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')) + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')) + + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan +} + +exports.Range = Range +function Range (range, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (range instanceof Range) { + if (range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + return new Range(range.value, options) + } + + if (!(this instanceof Range)) { + return new Range(range, options) + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First reduce all whitespace as much as possible so we do not have to rely + // on potentially slow regexes like \s*. This is then stored and used for + // future error messages as well. + this.raw = range + .trim() + .split(/\s+/) + .join(' ') + + // First, split based on boolean or || + this.set = this.raw.split('||').map(function (range) { + return this.parseRange(range.trim()) + }, this).filter(function (c) { + // throw out any that are not relevant for whatever reason + return c.length + }) + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + this.raw) + } + + this.format() +} + +Range.prototype.format = function () { + this.range = this.set.map(function (comps) { + return comps.join(' ').trim() + }).join('||').trim() + return this.range +} + +Range.prototype.toString = function () { + return this.range +} + +Range.prototype.parseRange = function (range) { + var loose = this.options.loose + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? safeRe[t.HYPHENRANGELOOSE] : safeRe[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(safeRe[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range, safeRe[t.COMPARATORTRIM]) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(safeRe[t.TILDETRIM], tildeTrimReplace) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(safeRe[t.CARETTRIM], caretTrimReplace) + + // normalize spaces + range = range.split(/\s+/).join(' ') + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR] + var set = range.split(' ').map(function (comp) { + return parseComparator(comp, this.options) + }, this).join(' ').split(/\s+/) + if (this.options.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function (comp) { + return !!comp.match(compRe) + }) + } + set = set.map(function (comp) { + return new Comparator(comp, this.options) + }, this) + + return set +} + +Range.prototype.intersects = function (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some(function (thisComparators) { + return ( + isSatisfiable(thisComparators, options) && + range.set.some(function (rangeComparators) { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every(function (thisComparator) { + return rangeComparators.every(function (rangeComparator) { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) +} + +// take a set of comparators and determine whether there +// exists a version which can satisfy it +function isSatisfiable (comparators, options) { + var result = true + var remainingComparators = comparators.slice() + var testComparator = remainingComparators.pop() + + while (result && remainingComparators.length) { + result = remainingComparators.every(function (otherComparator) { + return testComparator.intersects(otherComparator, options) + }) + + testComparator = remainingComparators.pop() + } + + return result +} + +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators +function toComparators (range, options) { + return new Range(range, options).set.map(function (comp) { + return comp.map(function (c) { + return c.value + }).join(' ').trim().split(' ') + }) +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator (comp, options) { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +function isX (id) { + return !id || id.toLowerCase() === 'x' || id === '*' +} + +// ~, ~> --> * (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 ? safeRe[t.TILDELOOSE] : safeRe[t.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 ? safeRe[t.CARETLOOSE] : safeRe[t.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 ? safeRe[t.XRANGELOOSE] : safeRe[t.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 we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.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 + pr + } else if (xm) { + ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr + } else if (xp) { + ret = '>=' + M + '.' + m + '.0' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + pr + } + + 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(safeRe[t.STAR], '') +} + +// This function is passed to string.replace(re[t.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') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + 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, options) { + if (version instanceof SemVer) { + return version + } + + if (typeof version === 'number') { + version = String(version) + } + + if (typeof version !== 'string') { + return null + } + + options = options || {} + + var match = null + if (!options.rtl) { + match = version.match(safeRe[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + var next + while ((next = safeRe[t.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + safeRe[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length + } + // leave it in a clean state + safeRe[t.COERCERTL].lastIndex = -1 + } + + if (match === null) { + return null + } + + return parse(match[2] + + '.' + (match[3] || '0') + + '.' + (match[4] || '0'), options) +} diff --git a/node_modules/eslint-plugin-react/package.json b/node_modules/eslint-plugin-react/package.json new file mode 100644 index 0000000000000000000000000000000000000000..56a2abf018da0172a897ada6065308569c46d5b2 --- /dev/null +++ b/node_modules/eslint-plugin-react/package.json @@ -0,0 +1,125 @@ +{ + "name": "eslint-plugin-react", + "version": "7.37.5", + "author": "Yannick Croissant ", + "description": "React specific linting rules for ESLint", + "main": "index.js", + "types": "index.d.ts", + "scripts": { + "clean-built-types": "rm -f $(find . -maxdepth 1 -type f -name '*.d.ts*') $(find lib -type f -name '*.d.ts*' ! -name 'types.d.ts')", + "prebuild-types": "npm run clean-built-types", + "build-types": "tsc -p build.tsconfig.json", + "prepack": "npm run build-types && npmignore --auto --commentLines=autogenerated", + "prelint": "npm run lint:docs", + "lint:docs": "markdownlint \"**/*.md\"", + "postlint:docs": "npm run update:eslint-docs -- --check", + "lint": "eslint .", + "postlint": "npm run type-check", + "pretest": "npm run lint", + "test": "npm run unit-test", + "posttest": "npx npm@'>= 10.2' audit --production", + "type-check": "tsc", + "unit-test": "istanbul cover node_modules/mocha/bin/_mocha tests/lib/**/*.js tests/util/**/*.js tests/index.js tests/flat-config.js", + "update:eslint-docs": "eslint-doc-generator" + }, + "repository": { + "type": "git", + "url": "https://github.com/jsx-eslint/eslint-plugin-react" + }, + "directories": { + "test": [ + "test", + "tests", + "test-published-types" + ] + }, + "homepage": "https://github.com/jsx-eslint/eslint-plugin-react", + "bugs": "https://github.com/jsx-eslint/eslint-plugin-react/issues", + "dependencies": { + "array-includes": "^3.1.8", + "array.prototype.findlast": "^1.2.5", + "array.prototype.flatmap": "^1.3.3", + "array.prototype.tosorted": "^1.1.4", + "doctrine": "^2.1.0", + "es-iterator-helpers": "^1.2.1", + "estraverse": "^5.3.0", + "hasown": "^2.0.2", + "jsx-ast-utils": "^2.4.1 || ^3.0.0", + "minimatch": "^3.1.2", + "object.entries": "^1.1.9", + "object.fromentries": "^2.0.8", + "object.values": "^1.2.1", + "prop-types": "^15.8.1", + "resolve": "^2.0.0-next.5", + "semver": "^6.3.1", + "string.prototype.matchall": "^4.0.12", + "string.prototype.repeat": "^1.0.0" + }, + "devDependencies": { + "@babel/core": "^7.26.10", + "@babel/eslint-parser": "^7.27.0", + "@babel/plugin-syntax-decorators": "^7.25.9", + "@babel/plugin-syntax-do-expressions": "^7.25.9", + "@babel/plugin-syntax-function-bind": "^7.25.9", + "@babel/preset-react": "^7.26.3", + "@types/eslint": "=7.2.10", + "@types/estree": "0.0.52", + "@types/node": "^4.9.5", + "@typescript-eslint/parser": "^2.34.0 || ^3.10.1 || ^4 || ^5 || ^6.20 || ^7.14.1 || 8.4 - 8.17", + "babel-eslint": "^8 || ^9 || ^10.1.0", + "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7", + "eslint-config-airbnb-base": "^15.0.0", + "eslint-doc-generator": "^1.7.1", + "eslint-plugin-eslint-plugin": "^2.3.0 || ^3.5.3 || ^4.0.1 || ^5.0.5", + "eslint-plugin-import": "^2.31.0", + "eslint-remote-tester": "^3.0.1", + "eslint-remote-tester-repositories": "^1.0.1", + "eslint-scope": "^3.7.3", + "espree": "^3.5.4", + "gfm-footnotes": "^1.0.1", + "glob": "=10.3.7", + "istanbul": "^0.4.5", + "jackspeak": "=2.1.1", + "ls-engines": "^0.8.1", + "markdownlint-cli": "^0.8.0 || ^0.32.2", + "mocha": "^5.2.0", + "npmignore": "^0.3.1", + "sinon": "^7.5.0", + "typescript": "^3.9.9", + "typescript-eslint-parser": "^20.1.1" + }, + "peerDependencies": { + "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7" + }, + "engines": { + "node": ">=4" + }, + "keywords": [ + "eslint", + "eslint-plugin", + "eslintplugin", + "react" + ], + "license": "MIT", + "publishConfig": { + "ignore": [ + ".github/", + "!lib", + "docs/", + "test/", + "test-published-types/", + "tests/", + "*.md", + "*.config.js", + ".eslint-doc-generatorrc.js", + ".eslintrc", + ".editorconfig", + "tsconfig.json", + "build.tsconfig.json", + ".markdownlint*", + "types", + "!*.d.ts", + "!*.d.ts.map" + ] + } +} diff --git a/node_modules/eslint-scope/LICENSE b/node_modules/eslint-scope/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d36a526f7ed5d10c43c68f34622efba7e62fc8a7 --- /dev/null +++ b/node_modules/eslint-scope/LICENSE @@ -0,0 +1,22 @@ +Copyright JS Foundation and other contributors, https://js.foundation +Copyright (C) 2012-2013 Yusuke Suzuki (twitter: @Constellation) and other contributors. + +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. + +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 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. diff --git a/node_modules/eslint-scope/README.md b/node_modules/eslint-scope/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e5b6a24a3d80270d82685c388007497e71eef066 --- /dev/null +++ b/node_modules/eslint-scope/README.md @@ -0,0 +1,198 @@ +[![npm version](https://img.shields.io/npm/v/eslint-scope.svg)](https://www.npmjs.com/package/eslint-scope) +[![Downloads](https://img.shields.io/npm/dm/eslint-scope.svg)](https://www.npmjs.com/package/eslint-scope) +[![Build Status](https://github.com/eslint/js/workflows/CI/badge.svg)](https://github.com/eslint/js/actions) + +# ESLint Scope + +ESLint Scope is the [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) scope analyzer used in ESLint. It is a fork of [escope](http://github.com/estools/escope). + +## Install + +``` +npm i eslint-scope --save +``` + +## 📖 Usage + +To use in an ESM file: + +```js +import * as eslintScope from 'eslint-scope'; +``` + +To use in a CommonJS file: + +```js +const eslintScope = require('eslint-scope'); +``` + +In order to analyze scope, you'll need to have an [ESTree](https://github.com/estree/estree) compliant AST structure to run it on. The primary method is `eslintScope.analyze()`, which takes two arguments: + +1. `ast` - the ESTree-compliant AST structure to analyze. +2. `options` (optional) - Options to adjust how the scope is analyzed, including: + * `ignoreEval` (default: `false`) - Set to `true` to ignore all `eval()` calls (which would normally create scopes). + * `nodejsScope` (default: `false`) - Set to `true` to create a top-level function scope needed for CommonJS evaluation. + * `impliedStrict` (default: `false`) - Set to `true` to evaluate the code in strict mode even outside of modules and without `"use strict"`. + * `ecmaVersion` (default: `5`) - The version of ECMAScript to use to evaluate the code. + * `sourceType` (default: `"script"`) - The type of JavaScript file to evaluate. Change to `"module"` for ECMAScript module code. + * `childVisitorKeys` (default: `null`) - An object with visitor key information (like [`eslint-visitor-keys`](https://github.com/eslint/js/tree/main/packages/eslint-visitor-keys)). Without this, `eslint-scope` finds child nodes to visit algorithmically. Providing this option is a performance enhancement. + * `fallback` (default: `"iteration"`) - The strategy to use when `childVisitorKeys` is not specified. May be a function. + * `jsx` (default: `false`) - Enables the tracking of JSX components as variable references. + +Example: + +```js +import * as eslintScope from 'eslint-scope'; +import * as espree from 'espree'; +import estraverse from 'estraverse'; + +const options = { + ecmaVersion: 2022, + sourceType: "module" +}; + +const ast = espree.parse(code, { range: true, ...options }); +const scopeManager = eslintScope.analyze(ast, options); + +const currentScope = scopeManager.acquire(ast); // global scope + +estraverse.traverse(ast, { + enter (node, parent) { + // do stuff + + if (/Function/.test(node.type)) { + currentScope = scopeManager.acquire(node); // get current function scope + } + }, + leave(node, parent) { + if (/Function/.test(node.type)) { + currentScope = currentScope.upper; // set to parent scope + } + + // do stuff + } +}); +``` + +## API + +The following section describes the API for this package. You can also read [the docs](https://eslint.org/docs/latest/extend/scope-manager-interface). + +### ScopeManager + +The `ScopeManager` class is at the core of eslint-scope and is returned when you call `eslintScope.analyze()`. It manages all scopes in a given AST. + +#### Properties + +- `scopes` - An array of all scopes. +- `globalScope` - Reference to the global scope. + +#### Methods + +- **`acquire(node, inner)`** + Acquires the appropriate scope for a given node. + - `node` - The AST node to acquire the scope from. + - `inner` - Optional boolean. When `true`, returns the innermost scope, otherwise returns the outermost scope. Default is `false`. + - Returns: The acquired scope or `null` if no scope is found. + +- **`acquireAll(node)`** + Acquires all scopes for a given node. + - `node` - The AST node to acquire scopes from. + - Returns: An array of scopes or `undefined` if none are found. + +- **`release(node, inner)`** + Returns the upper scope for a given node. + - `node` - The AST node to release. + - `inner` - Optional boolean. When `true`, returns the innermost upper scope, otherwise returns the outermost upper scope. Default is `false`. + - Returns: The upper scope or `null` if no upper scope exists. + +- **`getDeclaredVariables(node)`** + Get variables that are declared by the node. + - `node` - The AST node to get declarations from. + - Returns: An array of variable objects declared by the node. If the node doesn't declare any variables, it returns an empty array. + +- **`isGlobalReturn()`** + Determines if the global return statement should be allowed. + - Returns: `true` if the global return is enabled. + +- **`isModule()`** + Checks if the code should be handled as an ECMAScript module. + - Returns: `true` if the sourceType is "module". + +- **`isImpliedStrict()`** + Checks if implied strict mode is enabled. + - Returns: `true` if implied strict mode is enabled. + +- **`isStrictModeSupported()`** + Checks if strict mode is supported based on ECMAScript version. + - Returns: `true` if the ECMAScript version supports strict mode. + +### Scope Objects + +Scopes returned by the ScopeManager methods have the following properties: + +- `type` - The type of scope (e.g., "function", "block", "global"). +- `variables` - Array of variables declared in this scope. +- `set` - A Map of variable names to Variable objects for variables declared in this scope. +- `references` - Array of references in this scope. +- `through` - Array of references in this scope and its child scopes that aren't resolved in this scope or its child scopes. +- `variableScope` - Reference to the closest variable scope. +- `upper` - Reference to the parent scope. +- `childScopes` - Array of child scopes. +- `block` - The AST node that created this scope. + +### GlobalScope + +The `GlobalScope` class is a specialized scope representing the global execution context. It extends the base `Scope` class with additional functionality for handling implicitly defined global variables. + +#### Properties + +- **`implicit`** - Tracks implicitly defined global variables (those used without declaration). + - `set` - A Map of variable names to Variable objects for implicitly defined globals. + - `variables` - Array of implicit global Variable objects. + - `left` - Array of References that need to be linked to the variable they refer to. + +### Variable Objects + +Each variable object has the following properties: + +- `name` - The variable name. +- `identifiers` - Array of identifier nodes declaring this variable. +- `references` - Array of references to this variable. +- `defs` - Array of definition objects for this variable. +- `scope` - The scope object where this variable is defined. + +## Contributing + +Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/js/issues). + +## Security Policy + +We work hard to ensure that ESLint Scope is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md). + +## Build Commands + +* `npm test` - run all linting and tests +* `npm run lint` - run all linting + +## License + +ESLint Scope is licensed under a permissive BSD 2-clause license. + + + +## Sponsors + +The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate) +to get your logo on our READMEs and [website](https://eslint.org/sponsors). + +

Diamond Sponsors

+

AG Grid

Platinum Sponsors

+

Automattic Airbnb

Gold Sponsors

+

Qlty Software trunk.io Shopify

Silver Sponsors

+

Vite Liftoff American Express StackBlitz

Bronze Sponsors

+

Sentry Syntax Cybozu Anagram Solver Icons8 Discord GitBook Neko Nx Mercedes-Benz Group HeroCoders LambdaTest

+

Technology Sponsors

+Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work. +

Netlify Algolia 1Password

+ diff --git a/node_modules/eslint-scope/dist/eslint-scope.cjs b/node_modules/eslint-scope/dist/eslint-scope.cjs new file mode 100644 index 0000000000000000000000000000000000000000..abb88e5908461aca0ee0c6df5740d17c4d969e6b --- /dev/null +++ b/node_modules/eslint-scope/dist/eslint-scope.cjs @@ -0,0 +1,2339 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var estraverse = require('estraverse'); +var esrecurse = require('esrecurse'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var estraverse__default = /*#__PURE__*/_interopDefaultLegacy(estraverse); +var esrecurse__default = /*#__PURE__*/_interopDefaultLegacy(esrecurse); + +/** + * @fileoverview Assertion utilities. + * @author Nicholas C. Zakas + */ + +/** + * Throws an error if the given condition is not truthy. + * @param {boolean} condition The condition to check. + * @param {string} message The message to include with the error. + * @returns {void} + * @throws {Error} When the condition is not truthy. + */ +function assert(condition, message = "Assertion failed.") { + if (!condition) { + throw new Error(message); + } +} + +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ + +const READ = 0x1; +const WRITE = 0x2; +const RW = READ | WRITE; + +/** + * A Reference represents a single occurrence of an identifier in code. + * @constructor Reference + */ +class Reference { + constructor(ident, scope, flag, writeExpr, maybeImplicitGlobal, partial, init) { + + /** + * Identifier syntax node. + * @member {espreeIdentifier} Reference#identifier + */ + this.identifier = ident; + + /** + * Reference to the enclosing Scope. + * @member {Scope} Reference#from + */ + this.from = scope; + + /** + * Whether the reference comes from a dynamic scope (such as 'eval', + * 'with', etc.), and may be trapped by dynamic scopes. + * @member {boolean} Reference#tainted + */ + this.tainted = false; + + /** + * The variable this reference is resolved with. + * @member {Variable} Reference#resolved + */ + this.resolved = null; + + /** + * The read-write mode of the reference. (Value is one of {@link + * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}). + * @member {number} Reference#flag + * @private + */ + this.flag = flag; + if (this.isWrite()) { + + /** + * If reference is writeable, this is the tree being written to it. + * @member {espreeNode} Reference#writeExpr + */ + this.writeExpr = writeExpr; + + /** + * Whether the Reference might refer to a partial value of writeExpr. + * @member {boolean} Reference#partial + */ + this.partial = partial; + + /** + * Whether the Reference is to write of initialization. + * @member {boolean} Reference#init + */ + this.init = init; + } + this.__maybeImplicitGlobal = maybeImplicitGlobal; + } + + /** + * Whether the reference is static. + * @function Reference#isStatic + * @returns {boolean} static + */ + isStatic() { + return !this.tainted && this.resolved && this.resolved.scope.isStatic(); + } + + /** + * Whether the reference is writeable. + * @function Reference#isWrite + * @returns {boolean} write + */ + isWrite() { + return !!(this.flag & Reference.WRITE); + } + + /** + * Whether the reference is readable. + * @function Reference#isRead + * @returns {boolean} read + */ + isRead() { + return !!(this.flag & Reference.READ); + } + + /** + * Whether the reference is read-only. + * @function Reference#isReadOnly + * @returns {boolean} read only + */ + isReadOnly() { + return this.flag === Reference.READ; + } + + /** + * Whether the reference is write-only. + * @function Reference#isWriteOnly + * @returns {boolean} write only + */ + isWriteOnly() { + return this.flag === Reference.WRITE; + } + + /** + * Whether the reference is read-write. + * @function Reference#isReadWrite + * @returns {boolean} read write + */ + isReadWrite() { + return this.flag === Reference.RW; + } +} + +/** + * @constant Reference.READ + * @private + */ +Reference.READ = READ; + +/** + * @constant Reference.WRITE + * @private + */ +Reference.WRITE = WRITE; + +/** + * @constant Reference.RW + * @private + */ +Reference.RW = RW; + +/* vim: set sw=4 ts=4 et tw=80 : */ + +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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 Variable represents a locally scoped identifier. These include arguments to + * functions. + * @constructor Variable + */ +class Variable { + constructor(name, scope) { + + /** + * The variable name, as given in the source code. + * @member {string} Variable#name + */ + this.name = name; + + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as AST nodes. + * @member {espree.Identifier[]} Variable#identifiers + */ + this.identifiers = []; + + /** + * List of {@link Reference|references} of this variable (excluding parameter entries) + * in its defining scope and all nested scopes. For defining + * occurrences only see {@link Variable#defs}. + * @member {Reference[]} Variable#references + */ + this.references = []; + + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as custom objects. + * @member {Definition[]} Variable#defs + */ + this.defs = []; + + this.tainted = false; + + /** + * Whether this is a stack variable. + * @member {boolean} Variable#stack + */ + this.stack = true; + + /** + * Reference to the enclosing Scope. + * @member {Scope} Variable#scope + */ + this.scope = scope; + } +} + +Variable.CatchClause = "CatchClause"; +Variable.Parameter = "Parameter"; +Variable.FunctionName = "FunctionName"; +Variable.ClassName = "ClassName"; +Variable.Variable = "Variable"; +Variable.ImportBinding = "ImportBinding"; +Variable.ImplicitGlobalVariable = "ImplicitGlobalVariable"; + +/* vim: set sw=4 ts=4 et tw=80 : */ + +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ + +/** + * @constructor Definition + */ +class Definition { + constructor(type, name, node, parent, index, kind) { + + /** + * @member {string} Definition#type - type of the occurrence (e.g. "Parameter", "Variable", ...). + */ + this.type = type; + + /** + * @member {espree.Identifier} Definition#name - the identifier AST node of the occurrence. + */ + this.name = name; + + /** + * @member {espree.Node} Definition#node - the enclosing node of the identifier. + */ + this.node = node; + + /** + * @member {espree.Node?} Definition#parent - the enclosing statement node of the identifier. + */ + this.parent = parent; + + /** + * @member {number?} Definition#index - the index in the declaration statement. + */ + this.index = index; + + /** + * @member {string?} Definition#kind - the kind of the declaration statement. + */ + this.kind = kind; + } +} + +/** + * @constructor ParameterDefinition + */ +class ParameterDefinition extends Definition { + constructor(name, node, index, rest) { + super(Variable.Parameter, name, node, null, index, null); + + /** + * Whether the parameter definition is a part of a rest parameter. + * @member {boolean} ParameterDefinition#rest + */ + this.rest = rest; + } +} + +/* vim: set sw=4 ts=4 et tw=80 : */ + +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ + +const { Syntax: Syntax$2 } = estraverse__default["default"]; + +/** + * Test if scope is struct + * @param {Scope} scope scope + * @param {Block} block block + * @param {boolean} isMethodDefinition is method definition + * @returns {boolean} is strict scope + */ +function isStrictScope(scope, block, isMethodDefinition) { + let body; + + // When upper scope is exists and strict, inner scope is also strict. + if (scope.upper && scope.upper.isStrict) { + return true; + } + + if (isMethodDefinition) { + return true; + } + + if (scope.type === "class" || scope.type === "module") { + return true; + } + + if (scope.type === "block" || scope.type === "switch") { + return false; + } + + if (scope.type === "function") { + if (block.type === Syntax$2.ArrowFunctionExpression && block.body.type !== Syntax$2.BlockStatement) { + return false; + } + + if (block.type === Syntax$2.Program) { + body = block; + } else { + body = block.body; + } + + if (!body) { + return false; + } + } else if (scope.type === "global") { + body = block; + } else { + return false; + } + + // Search for a 'use strict' directive. + for (let i = 0, iz = body.body.length; i < iz; ++i) { + const stmt = body.body[i]; + + /* + * Check if the current statement is a directive. + * If it isn't, then we're past the directive prologue + * so stop the search because directives cannot + * appear after this point. + * + * Some parsers set `directive:null` on non-directive + * statements, so the `typeof` check is safer than + * checking for property existence. + */ + if (typeof stmt.directive !== "string") { + break; + } + + if (stmt.directive === "use strict") { + return true; + } + } + + return false; +} + +/** + * Register scope + * @param {ScopeManager} scopeManager scope manager + * @param {Scope} scope scope + * @returns {void} + */ +function registerScope(scopeManager, scope) { + scopeManager.scopes.push(scope); + + const scopes = scopeManager.__nodeToScope.get(scope.block); + + if (scopes) { + scopes.push(scope); + } else { + scopeManager.__nodeToScope.set(scope.block, [scope]); + } +} + +/** + * Should be statically + * @param {Object} def def + * @returns {boolean} should be statically + */ +function shouldBeStatically(def) { + return ( + (def.type === Variable.ClassName) || + (def.type === Variable.Variable && def.parent.kind !== "var") + ); +} + +/** + * @constructor Scope + */ +class Scope { + constructor(scopeManager, type, upperScope, block, isMethodDefinition) { + + /** + * One of "global", "module", "function", "function-expression-name", "block", "switch", "catch", "with", "for", + * "class", "class-field-initializer", "class-static-block". + * @member {string} Scope#type + */ + this.type = type; + + /** + * The scoped {@link Variable}s of this scope, as { Variable.name + * : Variable }. + * @member {Map} Scope#set + */ + this.set = new Map(); + + /** + * The tainted variables of this scope, as { Variable.name : + * boolean }. + * @member {Map} Scope#taints + */ + this.taints = new Map(); + + /** + * Generally, through the lexical scoping of JS you can always know + * which variable an identifier in the source code refers to. There are + * a few exceptions to this rule. With 'global' and 'with' scopes you + * can only decide at runtime which variable a reference refers to. + * Moreover, if 'eval()' is used in a scope, it might introduce new + * bindings in this or its parent scopes. + * All those scopes are considered 'dynamic'. + * @member {boolean} Scope#dynamic + */ + this.dynamic = this.type === "global" || this.type === "with"; + + /** + * A reference to the scope-defining syntax node. + * @member {espree.Node} Scope#block + */ + this.block = block; + + /** + * The {@link Reference|references} that are not resolved with this scope. + * @member {Reference[]} Scope#through + */ + this.through = []; + + /** + * The scoped {@link Variable}s of this scope. In the case of a + * 'function' scope this includes the automatic argument arguments as + * its first element, as well as all further formal arguments. + * @member {Variable[]} Scope#variables + */ + this.variables = []; + + /** + * Any variable {@link Reference|reference} found in this scope. This + * includes occurrences of local variables as well as variables from + * parent scopes (including the global scope). For local variables + * this also includes defining occurrences (like in a 'var' statement). + * In a 'function' scope this does not include the occurrences of the + * formal parameter in the parameter list. + * @member {Reference[]} Scope#references + */ + this.references = []; + + /** + * For 'global' and 'function' scopes, this is a self-reference. For + * other scope types this is the variableScope value of the + * parent scope. + * @member {Scope} Scope#variableScope + */ + this.variableScope = + this.type === "global" || + this.type === "module" || + this.type === "function" || + this.type === "class-field-initializer" || + this.type === "class-static-block" + ? this + : upperScope.variableScope; + + /** + * Whether this scope is created by a FunctionExpression. + * @member {boolean} Scope#functionExpressionScope + */ + this.functionExpressionScope = false; + + /** + * Whether this is a scope that contains an 'eval()' invocation. + * @member {boolean} Scope#directCallToEvalScope + */ + this.directCallToEvalScope = false; + + /** + * @member {boolean} Scope#thisFound + */ + this.thisFound = false; + + this.__left = []; + + /** + * Reference to the parent {@link Scope|scope}. + * @member {Scope} Scope#upper + */ + this.upper = upperScope; + + /** + * Whether 'use strict' is in effect in this scope. + * @member {boolean} Scope#isStrict + */ + this.isStrict = scopeManager.isStrictModeSupported() + ? isStrictScope(this, block, isMethodDefinition) + : false; + + /** + * List of nested {@link Scope}s. + * @member {Scope[]} Scope#childScopes + */ + this.childScopes = []; + if (this.upper) { + this.upper.childScopes.push(this); + } + + this.__declaredVariables = scopeManager.__declaredVariables; + + registerScope(scopeManager, this); + } + + __shouldStaticallyClose(scopeManager) { + return (!this.dynamic || scopeManager.__isOptimistic()); + } + + __shouldStaticallyCloseForGlobal(ref) { + + // On global scope, let/const/class declarations should be resolved statically. + const name = ref.identifier.name; + + if (!this.set.has(name)) { + return false; + } + + const variable = this.set.get(name); + const defs = variable.defs; + + return defs.length > 0 && defs.every(shouldBeStatically); + } + + __staticCloseRef(ref) { + if (!this.__resolve(ref)) { + this.__delegateToUpperScope(ref); + } + } + + __dynamicCloseRef(ref) { + + // notify all names are through to global + let current = this; + + do { + current.through.push(ref); + current = current.upper; + } while (current); + } + + __globalCloseRef(ref) { + + // let/const/class declarations should be resolved statically. + // others should be resolved dynamically. + if (this.__shouldStaticallyCloseForGlobal(ref)) { + this.__staticCloseRef(ref); + } else { + this.__dynamicCloseRef(ref); + } + } + + __close(scopeManager) { + let closeRef; + + if (this.__shouldStaticallyClose(scopeManager)) { + closeRef = this.__staticCloseRef; + } else if (this.type !== "global") { + closeRef = this.__dynamicCloseRef; + } else { + closeRef = this.__globalCloseRef; + } + + // Try Resolving all references in this scope. + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; + + closeRef.call(this, ref); + } + this.__left = null; + + return this.upper; + } + + // To override by function scopes. + // References in default parameters isn't resolved to variables which are in their function body. + __isValidResolution(ref, variable) { // eslint-disable-line class-methods-use-this, no-unused-vars -- Desired as instance method with signature + return true; + } + + __resolve(ref) { + const name = ref.identifier.name; + + if (!this.set.has(name)) { + return false; + } + const variable = this.set.get(name); + + if (!this.__isValidResolution(ref, variable)) { + return false; + } + variable.references.push(ref); + variable.stack = variable.stack && ref.from.variableScope === this.variableScope; + if (ref.tainted) { + variable.tainted = true; + this.taints.set(variable.name, true); + } + ref.resolved = variable; + + return true; + } + + __delegateToUpperScope(ref) { + if (this.upper) { + this.upper.__left.push(ref); + } + this.through.push(ref); + } + + __addDeclaredVariablesOfNode(variable, node) { + if (node === null || node === void 0) { + return; + } + + let variables = this.__declaredVariables.get(node); + + if (variables === null || variables === void 0) { + variables = []; + this.__declaredVariables.set(node, variables); + } + if (!variables.includes(variable)) { + variables.push(variable); + } + } + + __defineGeneric(name, set, variables, node, def) { + let variable; + + variable = set.get(name); + if (!variable) { + variable = new Variable(name, this); + set.set(name, variable); + variables.push(variable); + } + + if (def) { + variable.defs.push(def); + this.__addDeclaredVariablesOfNode(variable, def.node); + this.__addDeclaredVariablesOfNode(variable, def.parent); + } + if (node) { + variable.identifiers.push(node); + } + } + + __define(node, def) { + if (node && node.type === Syntax$2.Identifier) { + this.__defineGeneric( + node.name, + this.set, + this.variables, + node, + def + ); + } + } + + __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial, init) { + + // because Array element may be null + if (!node || (node.type !== Syntax$2.Identifier && node.type !== "JSXIdentifier")) { + return; + } + + // Specially handle like `this`. + if (node.name === "super") { + return; + } + + const ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial, !!init); + + this.references.push(ref); + this.__left.push(ref); + } + + __detectEval() { + let current = this; + + this.directCallToEvalScope = true; + do { + current.dynamic = true; + current = current.upper; + } while (current); + } + + __detectThis() { + this.thisFound = true; + } + + __isClosed() { + return this.__left === null; + } + + /** + * returns resolved {Reference} + * @function Scope#resolve + * @param {Espree.Identifier} ident identifier to be resolved. + * @returns {Reference} reference + */ + resolve(ident) { + let ref, i, iz; + + assert(this.__isClosed(), "Scope should be closed."); + assert(ident.type === Syntax$2.Identifier, "Target should be identifier."); + for (i = 0, iz = this.references.length; i < iz; ++i) { + ref = this.references[i]; + if (ref.identifier === ident) { + return ref; + } + } + return null; + } + + /** + * returns this scope is static + * @function Scope#isStatic + * @returns {boolean} static + */ + isStatic() { + return !this.dynamic; + } + + /** + * returns this scope has materialized arguments + * @function Scope#isArgumentsMaterialized + * @returns {boolean} arguemnts materialized + */ + isArgumentsMaterialized() { // eslint-disable-line class-methods-use-this -- Desired as instance method + return true; + } + + /** + * returns this scope has materialized `this` reference + * @function Scope#isThisMaterialized + * @returns {boolean} this materialized + */ + isThisMaterialized() { // eslint-disable-line class-methods-use-this -- Desired as instance method + return true; + } + + isUsedName(name) { + if (this.set.has(name)) { + return true; + } + for (let i = 0, iz = this.through.length; i < iz; ++i) { + if (this.through[i].identifier.name === name) { + return true; + } + } + return false; + } +} + +/** + * Global scope. + */ +class GlobalScope extends Scope { + constructor(scopeManager, block) { + super(scopeManager, "global", null, block, false); + this.implicit = { + set: new Map(), + variables: [], + + /** + * List of {@link Reference}s that are left to be resolved (i.e. which + * need to be linked to the variable they refer to). + * @member {Reference[]} Scope#implicit#left + */ + left: [] + }; + } + + __close(scopeManager) { + const implicit = []; + + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; + + if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) { + implicit.push(ref.__maybeImplicitGlobal); + } + } + + // create an implicit global variable from assignment expression + for (let i = 0, iz = implicit.length; i < iz; ++i) { + const info = implicit[i]; + + this.__defineImplicit(info.pattern, + new Definition( + Variable.ImplicitGlobalVariable, + info.pattern, + info.node, + null, + null, + null + )); + + } + + this.implicit.left = this.__left; + + return super.__close(scopeManager); + } + + __defineImplicit(node, def) { + if (node && node.type === Syntax$2.Identifier) { + this.__defineGeneric( + node.name, + this.implicit.set, + this.implicit.variables, + node, + def + ); + } + } +} + +/** + * Module scope. + */ +class ModuleScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "module", upperScope, block, false); + } +} + +/** + * Function expression name scope. + */ +class FunctionExpressionNameScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "function-expression-name", upperScope, block, false); + this.__define(block.id, + new Definition( + Variable.FunctionName, + block.id, + block, + null, + null, + null + )); + this.functionExpressionScope = true; + } +} + +/** + * Catch scope. + */ +class CatchScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "catch", upperScope, block, false); + } +} + +/** + * With statement scope. + */ +class WithScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "with", upperScope, block, false); + } + + __close(scopeManager) { + if (this.__shouldStaticallyClose(scopeManager)) { + return super.__close(scopeManager); + } + + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; + + ref.tainted = true; + this.__delegateToUpperScope(ref); + } + this.__left = null; + + return this.upper; + } +} + +/** + * Block scope. + */ +class BlockScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "block", upperScope, block, false); + } +} + +/** + * Switch scope. + */ +class SwitchScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "switch", upperScope, block, false); + } +} + +/** + * Function scope. + */ +class FunctionScope extends Scope { + constructor(scopeManager, upperScope, block, isMethodDefinition) { + super(scopeManager, "function", upperScope, block, isMethodDefinition); + + // section 9.2.13, FunctionDeclarationInstantiation. + // NOTE Arrow functions never have an arguments objects. + if (this.block.type !== Syntax$2.ArrowFunctionExpression) { + this.__defineArguments(); + } + } + + isArgumentsMaterialized() { + + // TODO(Constellation) + // We can more aggressive on this condition like this. + // + // function t() { + // // arguments of t is always hidden. + // function arguments() { + // } + // } + if (this.block.type === Syntax$2.ArrowFunctionExpression) { + return false; + } + + if (!this.isStatic()) { + return true; + } + + const variable = this.set.get("arguments"); + + assert(variable, "Always have arguments variable."); + return variable.tainted || variable.references.length !== 0; + } + + isThisMaterialized() { + if (!this.isStatic()) { + return true; + } + return this.thisFound; + } + + __defineArguments() { + this.__defineGeneric( + "arguments", + this.set, + this.variables, + null, + null + ); + this.taints.set("arguments", true); + } + + // References in default parameters isn't resolved to variables which are in their function body. + // const x = 1 + // function f(a = x) { // This `x` is resolved to the `x` in the outer scope. + // const x = 2 + // console.log(a) + // } + __isValidResolution(ref, variable) { + + // If `options.nodejsScope` is true, `this.block` becomes a Program node. + if (this.block.type === "Program") { + return true; + } + + const bodyStart = this.block.body.range[0]; + + // It's invalid resolution in the following case: + return !( + variable.scope === this && + ref.identifier.range[0] < bodyStart && // the reference is in the parameter part. + variable.defs.every(d => d.name.range[0] >= bodyStart) // the variable is in the body. + ); + } +} + +/** + * Scope of for, for-in, and for-of statements. + */ +class ForScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "for", upperScope, block, false); + } +} + +/** + * Class scope. + */ +class ClassScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "class", upperScope, block, false); + } +} + +/** + * Class field initializer scope. + */ +class ClassFieldInitializerScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "class-field-initializer", upperScope, block, true); + } +} + +/** + * Class static block scope. + */ +class ClassStaticBlockScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "class-static-block", upperScope, block, true); + } +} + +/* vim: set sw=4 ts=4 et tw=80 : */ + +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ + +/** + * @constructor ScopeManager + */ +class ScopeManager { + constructor(options) { + this.scopes = []; + this.globalScope = null; + this.__nodeToScope = new WeakMap(); + this.__currentScope = null; + this.__options = options; + this.__declaredVariables = new WeakMap(); + } + + __isOptimistic() { + return this.__options.optimistic; + } + + __ignoreEval() { + return this.__options.ignoreEval; + } + + __isJSXEnabled() { + return this.__options.jsx === true; + } + + isGlobalReturn() { + return this.__options.nodejsScope || this.__options.sourceType === "commonjs"; + } + + isModule() { + return this.__options.sourceType === "module"; + } + + isImpliedStrict() { + return this.__options.impliedStrict; + } + + isStrictModeSupported() { + return this.__options.ecmaVersion >= 5; + } + + // Returns appropriate scope for this node. + __get(node) { + return this.__nodeToScope.get(node); + } + + /** + * Get variables that are declared by the node. + * + * "are declared by the node" means the node is same as `Variable.defs[].node` or `Variable.defs[].parent`. + * If the node declares nothing, this method returns an empty array. + * CAUTION: This API is experimental. See https://github.com/estools/escope/pull/69 for more details. + * @param {Espree.Node} node a node to get. + * @returns {Variable[]} variables that declared by the node. + */ + getDeclaredVariables(node) { + return this.__declaredVariables.get(node) || []; + } + + /** + * acquire scope from node. + * @function ScopeManager#acquire + * @param {Espree.Node} node node for the acquired scope. + * @param {?boolean} [inner=false] look up the most inner scope, default value is false. + * @returns {Scope?} Scope from node + */ + acquire(node, inner) { + + /** + * predicate + * @param {Scope} testScope scope to test + * @returns {boolean} predicate + */ + function predicate(testScope) { + if (testScope.type === "function" && testScope.functionExpressionScope) { + return false; + } + return true; + } + + const scopes = this.__get(node); + + if (!scopes || scopes.length === 0) { + return null; + } + + // Heuristic selection from all scopes. + // If you would like to get all scopes, please use ScopeManager#acquireAll. + if (scopes.length === 1) { + return scopes[0]; + } + + if (inner) { + for (let i = scopes.length - 1; i >= 0; --i) { + const scope = scopes[i]; + + if (predicate(scope)) { + return scope; + } + } + } else { + for (let i = 0, iz = scopes.length; i < iz; ++i) { + const scope = scopes[i]; + + if (predicate(scope)) { + return scope; + } + } + } + + return null; + } + + /** + * acquire all scopes from node. + * @function ScopeManager#acquireAll + * @param {Espree.Node} node node for the acquired scope. + * @returns {Scopes?} Scope array + */ + acquireAll(node) { + return this.__get(node); + } + + /** + * release the node. + * @function ScopeManager#release + * @param {Espree.Node} node releasing node. + * @param {?boolean} [inner=false] look up the most inner scope, default value is false. + * @returns {Scope?} upper scope for the node. + */ + release(node, inner) { + const scopes = this.__get(node); + + if (scopes && scopes.length) { + const scope = scopes[0].upper; + + if (!scope) { + return null; + } + return this.acquire(scope.block, inner); + } + return null; + } + + attach() { } // eslint-disable-line class-methods-use-this -- Desired as instance method + + detach() { } // eslint-disable-line class-methods-use-this -- Desired as instance method + + __nestScope(scope) { + if (scope instanceof GlobalScope) { + assert(this.__currentScope === null); + this.globalScope = scope; + } + this.__currentScope = scope; + return scope; + } + + __nestGlobalScope(node) { + return this.__nestScope(new GlobalScope(this, node)); + } + + __nestBlockScope(node) { + return this.__nestScope(new BlockScope(this, this.__currentScope, node)); + } + + __nestFunctionScope(node, isMethodDefinition) { + return this.__nestScope(new FunctionScope(this, this.__currentScope, node, isMethodDefinition)); + } + + __nestForScope(node) { + return this.__nestScope(new ForScope(this, this.__currentScope, node)); + } + + __nestCatchScope(node) { + return this.__nestScope(new CatchScope(this, this.__currentScope, node)); + } + + __nestWithScope(node) { + return this.__nestScope(new WithScope(this, this.__currentScope, node)); + } + + __nestClassScope(node) { + return this.__nestScope(new ClassScope(this, this.__currentScope, node)); + } + + __nestClassFieldInitializerScope(node) { + return this.__nestScope(new ClassFieldInitializerScope(this, this.__currentScope, node)); + } + + __nestClassStaticBlockScope(node) { + return this.__nestScope(new ClassStaticBlockScope(this, this.__currentScope, node)); + } + + __nestSwitchScope(node) { + return this.__nestScope(new SwitchScope(this, this.__currentScope, node)); + } + + __nestModuleScope(node) { + return this.__nestScope(new ModuleScope(this, this.__currentScope, node)); + } + + __nestFunctionExpressionNameScope(node) { + return this.__nestScope(new FunctionExpressionNameScope(this, this.__currentScope, node)); + } + + __isES6() { + return this.__options.ecmaVersion >= 6; + } +} + +/* vim: set sw=4 ts=4 et tw=80 : */ + +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ + +const { Syntax: Syntax$1 } = estraverse__default["default"]; + +/** + * Get last array element + * @param {Array} xs array + * @returns {any} Last elment + */ +function getLast(xs) { + return xs.at(-1) || null; +} + +/** + * Visitor for destructuring patterns. + */ +class PatternVisitor extends esrecurse__default["default"].Visitor { + static isPattern(node) { + const nodeType = node.type; + + return ( + nodeType === Syntax$1.Identifier || + nodeType === Syntax$1.ObjectPattern || + nodeType === Syntax$1.ArrayPattern || + nodeType === Syntax$1.SpreadElement || + nodeType === Syntax$1.RestElement || + nodeType === Syntax$1.AssignmentPattern + ); + } + + constructor(options, rootPattern, callback) { + super(null, options); + this.rootPattern = rootPattern; + this.callback = callback; + this.assignments = []; + this.rightHandNodes = []; + this.restElements = []; + } + + Identifier(pattern) { + const lastRestElement = getLast(this.restElements); + + this.callback(pattern, { + topLevel: pattern === this.rootPattern, + rest: lastRestElement !== null && lastRestElement !== void 0 && lastRestElement.argument === pattern, + assignments: this.assignments + }); + } + + Property(property) { + + // Computed property's key is a right hand node. + if (property.computed) { + this.rightHandNodes.push(property.key); + } + + // If it's shorthand, its key is same as its value. + // If it's shorthand and has its default value, its key is same as its value.left (the value is AssignmentPattern). + // If it's not shorthand, the name of new variable is its value's. + this.visit(property.value); + } + + ArrayPattern(pattern) { + for (let i = 0, iz = pattern.elements.length; i < iz; ++i) { + const element = pattern.elements[i]; + + this.visit(element); + } + } + + AssignmentPattern(pattern) { + this.assignments.push(pattern); + this.visit(pattern.left); + this.rightHandNodes.push(pattern.right); + this.assignments.pop(); + } + + RestElement(pattern) { + this.restElements.push(pattern); + this.visit(pattern.argument); + this.restElements.pop(); + } + + MemberExpression(node) { + + // Computed property's key is a right hand node. + if (node.computed) { + this.rightHandNodes.push(node.property); + } + + // the object is only read, write to its property. + this.rightHandNodes.push(node.object); + } + + // + // ForInStatement.left and AssignmentExpression.left are LeftHandSideExpression. + // By spec, LeftHandSideExpression is Pattern or MemberExpression. + // (see also: https://github.com/estree/estree/pull/20#issuecomment-74584758) + // But espree 2.0 parses to ArrayExpression, ObjectExpression, etc... + // + + SpreadElement(node) { + this.visit(node.argument); + } + + ArrayExpression(node) { + node.elements.forEach(this.visit, this); + } + + AssignmentExpression(node) { + this.assignments.push(node); + this.visit(node.left); + this.rightHandNodes.push(node.right); + this.assignments.pop(); + } + + CallExpression(node) { + + // arguments are right hand nodes. + node.arguments.forEach(a => { + this.rightHandNodes.push(a); + }); + this.visit(node.callee); + } +} + +/* vim: set sw=4 ts=4 et tw=80 : */ + +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ + +const { Syntax } = estraverse__default["default"]; + +/** + * Traverse identifier in pattern + * @param {Object} options options + * @param {pattern} rootPattern root pattern + * @param {Refencer} referencer referencer + * @param {callback} callback callback + * @returns {void} + */ +function traverseIdentifierInPattern(options, rootPattern, referencer, callback) { + + // Call the callback at left hand identifier nodes, and Collect right hand nodes. + const visitor = new PatternVisitor(options, rootPattern, callback); + + visitor.visit(rootPattern); + + // Process the right hand nodes recursively. + if (referencer !== null && referencer !== void 0) { + visitor.rightHandNodes.forEach(referencer.visit, referencer); + } +} + +// Importing ImportDeclaration. +// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-moduledeclarationinstantiation +// https://github.com/estree/estree/blob/master/es6.md#importdeclaration +// FIXME: Now, we don't create module environment, because the context is +// implementation dependent. + +/** + * Visitor for import specifiers. + */ +class Importer extends esrecurse__default["default"].Visitor { + constructor(declaration, referencer) { + super(null, referencer.options); + this.declaration = declaration; + this.referencer = referencer; + } + + visitImport(id, specifier) { + this.referencer.visitPattern(id, pattern => { + this.referencer.currentScope().__define(pattern, + new Definition( + Variable.ImportBinding, + pattern, + specifier, + this.declaration, + null, + null + )); + }); + } + + ImportNamespaceSpecifier(node) { + const local = (node.local || node.id); + + if (local) { + this.visitImport(local, node); + } + } + + ImportDefaultSpecifier(node) { + const local = (node.local || node.id); + + this.visitImport(local, node); + } + + ImportSpecifier(node) { + const local = (node.local || node.id); + + if (node.name) { + this.visitImport(node.name, node); + } else { + this.visitImport(local, node); + } + } +} + +/** + * Referencing variables and creating bindings. + */ +class Referencer extends esrecurse__default["default"].Visitor { + constructor(options, scopeManager) { + super(null, options); + this.options = options; + this.scopeManager = scopeManager; + this.parent = null; + this.isInnerMethodDefinition = false; + } + + currentScope() { + return this.scopeManager.__currentScope; + } + + close(node) { + while (this.currentScope() && node === this.currentScope().block) { + this.scopeManager.__currentScope = this.currentScope().__close(this.scopeManager); + } + } + + pushInnerMethodDefinition(isInnerMethodDefinition) { + const previous = this.isInnerMethodDefinition; + + this.isInnerMethodDefinition = isInnerMethodDefinition; + return previous; + } + + popInnerMethodDefinition(isInnerMethodDefinition) { + this.isInnerMethodDefinition = isInnerMethodDefinition; + } + + referencingDefaultValue(pattern, assignments, maybeImplicitGlobal, init) { + const scope = this.currentScope(); + + assignments.forEach(assignment => { + scope.__referencing( + pattern, + Reference.WRITE, + assignment.right, + maybeImplicitGlobal, + pattern !== assignment.left, + init + ); + }); + } + + visitPattern(node, options, callback) { + let visitPatternOptions = options; + let visitPatternCallback = callback; + + if (typeof options === "function") { + visitPatternCallback = options; + visitPatternOptions = { processRightHandNodes: false }; + } + + traverseIdentifierInPattern( + this.options, + node, + visitPatternOptions.processRightHandNodes ? this : null, + visitPatternCallback + ); + } + + visitFunction(node) { + let i, iz; + + // FunctionDeclaration name is defined in upper scope + // NOTE: Not referring variableScope. It is intended. + // Since + // in ES5, FunctionDeclaration should be in FunctionBody. + // in ES6, FunctionDeclaration should be block scoped. + + if (node.type === Syntax.FunctionDeclaration) { + + // id is defined in upper scope + this.currentScope().__define(node.id, + new Definition( + Variable.FunctionName, + node.id, + node, + null, + null, + null + )); + } + + // FunctionExpression with name creates its special scope; + // FunctionExpressionNameScope. + if (node.type === Syntax.FunctionExpression && node.id) { + this.scopeManager.__nestFunctionExpressionNameScope(node); + } + + // Consider this function is in the MethodDefinition. + this.scopeManager.__nestFunctionScope(node, this.isInnerMethodDefinition); + + const that = this; + + /** + * Visit pattern callback + * @param {pattern} pattern pattern + * @param {Object} info info + * @returns {void} + */ + function visitPatternCallback(pattern, info) { + that.currentScope().__define(pattern, + new ParameterDefinition( + pattern, + node, + i, + info.rest + )); + + that.referencingDefaultValue(pattern, info.assignments, null, true); + } + + // Process parameter declarations. + for (i = 0, iz = node.params.length; i < iz; ++i) { + this.visitPattern(node.params[i], { processRightHandNodes: true }, visitPatternCallback); + } + + // if there's a rest argument, add that + if (node.rest) { + this.visitPattern({ + type: "RestElement", + argument: node.rest + }, pattern => { + this.currentScope().__define(pattern, + new ParameterDefinition( + pattern, + node, + node.params.length, + true + )); + }); + } + + // In TypeScript there are a number of function-like constructs which have no body, + // so check it exists before traversing + if (node.body) { + + // Skip BlockStatement to prevent creating BlockStatement scope. + if (node.body.type === Syntax.BlockStatement) { + this.visitChildren(node.body); + } else { + this.visit(node.body); + } + } + + this.close(node); + } + + visitClass(node) { + if (node.type === Syntax.ClassDeclaration) { + this.currentScope().__define(node.id, + new Definition( + Variable.ClassName, + node.id, + node, + null, + null, + null + )); + } + + this.scopeManager.__nestClassScope(node); + + if (node.id) { + this.currentScope().__define(node.id, + new Definition( + Variable.ClassName, + node.id, + node + )); + } + + this.visit(node.superClass); + this.visit(node.body); + + this.close(node); + } + + visitProperty(node) { + let previous; + + if (node.computed) { + this.visit(node.key); + } + + const isMethodDefinition = node.type === Syntax.MethodDefinition; + + if (isMethodDefinition) { + previous = this.pushInnerMethodDefinition(true); + } + this.visit(node.value); + if (isMethodDefinition) { + this.popInnerMethodDefinition(previous); + } + } + + visitForIn(node) { + if (node.left.type === Syntax.VariableDeclaration && node.left.kind !== "var") { + this.scopeManager.__nestForScope(node); + } + + if (node.left.type === Syntax.VariableDeclaration) { + this.visit(node.left); + this.visitPattern(node.left.declarations[0].id, pattern => { + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, null, true, true); + }); + } else { + this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => { + let maybeImplicitGlobal = null; + + if (!this.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern, + node + }; + } + this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, true, false); + }); + } + this.visit(node.right); + this.visit(node.body); + + this.close(node); + } + + visitVariableDeclaration(variableTargetScope, type, node, index) { + + const decl = node.declarations[index]; + const init = decl.init; + + this.visitPattern(decl.id, { processRightHandNodes: true }, (pattern, info) => { + variableTargetScope.__define( + pattern, + new Definition( + type, + pattern, + decl, + node, + index, + node.kind + ) + ); + + this.referencingDefaultValue(pattern, info.assignments, null, true); + if (init) { + this.currentScope().__referencing(pattern, Reference.WRITE, init, null, !info.topLevel, true); + } + }); + } + + AssignmentExpression(node) { + if (PatternVisitor.isPattern(node.left)) { + if (node.operator === "=") { + this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => { + let maybeImplicitGlobal = null; + + if (!this.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern, + node + }; + } + this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, !info.topLevel, false); + }); + } else { + this.currentScope().__referencing(node.left, Reference.RW, node.right); + } + } else { + this.visit(node.left); + } + this.visit(node.right); + } + + CatchClause(node) { + this.scopeManager.__nestCatchScope(node); + + this.visitPattern(node.param, { processRightHandNodes: true }, (pattern, info) => { + this.currentScope().__define(pattern, + new Definition( + Variable.CatchClause, + pattern, + node, + null, + null, + null + )); + this.referencingDefaultValue(pattern, info.assignments, null, true); + }); + this.visit(node.body); + + this.close(node); + } + + Program(node) { + this.scopeManager.__nestGlobalScope(node); + + if (this.scopeManager.isGlobalReturn()) { + + // Force strictness of GlobalScope to false when using node.js scope. + this.currentScope().isStrict = false; + this.scopeManager.__nestFunctionScope(node, false); + } + + if (this.scopeManager.__isES6() && this.scopeManager.isModule()) { + this.scopeManager.__nestModuleScope(node); + } + + if (this.scopeManager.isStrictModeSupported() && this.scopeManager.isImpliedStrict()) { + this.currentScope().isStrict = true; + } + + this.visitChildren(node); + this.close(node); + } + + Identifier(node) { + this.currentScope().__referencing(node); + } + + // eslint-disable-next-line class-methods-use-this -- Desired as instance method + PrivateIdentifier() { + + // Do nothing. + } + + UpdateExpression(node) { + if (PatternVisitor.isPattern(node.argument)) { + this.currentScope().__referencing(node.argument, Reference.RW, null); + } else { + this.visitChildren(node); + } + } + + MemberExpression(node) { + this.visit(node.object); + if (node.computed) { + this.visit(node.property); + } + } + + Property(node) { + this.visitProperty(node); + } + + PropertyDefinition(node) { + const { computed, key, value } = node; + + if (computed) { + this.visit(key); + } + if (value) { + this.scopeManager.__nestClassFieldInitializerScope(value); + this.visit(value); + this.close(value); + } + } + + StaticBlock(node) { + this.scopeManager.__nestClassStaticBlockScope(node); + + this.visitChildren(node); + + this.close(node); + } + + MethodDefinition(node) { + this.visitProperty(node); + } + + BreakStatement() {} // eslint-disable-line class-methods-use-this -- Desired as instance method + + ContinueStatement() {} // eslint-disable-line class-methods-use-this -- Desired as instance method + + LabeledStatement(node) { + this.visit(node.body); + } + + ForStatement(node) { + + // Create ForStatement declaration. + // NOTE: In ES6, ForStatement dynamically generates + // per iteration environment. However, escope is + // a static analyzer, we only generate one scope for ForStatement. + if (node.init && node.init.type === Syntax.VariableDeclaration && node.init.kind !== "var") { + this.scopeManager.__nestForScope(node); + } + + this.visitChildren(node); + + this.close(node); + } + + ClassExpression(node) { + this.visitClass(node); + } + + ClassDeclaration(node) { + this.visitClass(node); + } + + CallExpression(node) { + + // Check this is direct call to eval + if (!this.scopeManager.__ignoreEval() && node.callee.type === Syntax.Identifier && node.callee.name === "eval") { + + // NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and + // let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment. + this.currentScope().variableScope.__detectEval(); + } + this.visitChildren(node); + } + + BlockStatement(node) { + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestBlockScope(node); + } + + this.visitChildren(node); + + this.close(node); + } + + ThisExpression() { + this.currentScope().variableScope.__detectThis(); + } + + WithStatement(node) { + this.visit(node.object); + + // Then nest scope for WithStatement. + this.scopeManager.__nestWithScope(node); + + this.visit(node.body); + + this.close(node); + } + + VariableDeclaration(node) { + const variableTargetScope = (node.kind === "var") ? this.currentScope().variableScope : this.currentScope(); + + for (let i = 0, iz = node.declarations.length; i < iz; ++i) { + const decl = node.declarations[i]; + + this.visitVariableDeclaration(variableTargetScope, Variable.Variable, node, i); + if (decl.init) { + this.visit(decl.init); + } + } + } + + // sec 13.11.8 + SwitchStatement(node) { + this.visit(node.discriminant); + + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestSwitchScope(node); + } + + for (let i = 0, iz = node.cases.length; i < iz; ++i) { + this.visit(node.cases[i]); + } + + this.close(node); + } + + FunctionDeclaration(node) { + this.visitFunction(node); + } + + FunctionExpression(node) { + this.visitFunction(node); + } + + ForOfStatement(node) { + this.visitForIn(node); + } + + ForInStatement(node) { + this.visitForIn(node); + } + + ArrowFunctionExpression(node) { + this.visitFunction(node); + } + + ImportDeclaration(node) { + assert(this.scopeManager.__isES6() && this.scopeManager.isModule(), "ImportDeclaration should appear when the mode is ES6 and in the module context."); + + const importer = new Importer(node, this); + + importer.visit(node); + } + + visitExportDeclaration(node) { + if (node.source) { + return; + } + if (node.declaration) { + this.visit(node.declaration); + return; + } + + this.visitChildren(node); + } + + // TODO: ExportDeclaration doesn't exist. for bc? + ExportDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportAllDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportDefaultDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportNamedDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportSpecifier(node) { + + // TODO: `node.id` doesn't exist. for bc? + const local = (node.id || node.local); + + this.visit(local); + } + + MetaProperty() { // eslint-disable-line class-methods-use-this -- Desired as instance method + + // do nothing. + } + + JSXIdentifier(node) { + + // Special case: "this" should not count as a reference + if (this.scopeManager.__isJSXEnabled() && node.name !== "this") { + this.currentScope().__referencing(node); + } + } + + JSXMemberExpression(node) { + this.visit(node.object); + } + + JSXElement(node) { + if (this.scopeManager.__isJSXEnabled()) { + this.visit(node.openingElement); + node.children.forEach(this.visit, this); + } else { + this.visitChildren(node); + } + } + + JSXOpeningElement(node) { + if (this.scopeManager.__isJSXEnabled()) { + + const nameNode = node.name; + const isComponentName = nameNode.type === "JSXIdentifier" && nameNode.name[0].toUpperCase() === nameNode.name[0]; + const isComponent = isComponentName || nameNode.type === "JSXMemberExpression"; + + // we only want to visit JSXIdentifier nodes if they are capitalized + if (isComponent) { + this.visit(nameNode); + } + } + + node.attributes.forEach(this.visit, this); + } + + JSXAttribute(node) { + if (node.value) { + this.visit(node.value); + } + } + + JSXExpressionContainer(node) { + this.visit(node.expression); + } + + JSXNamespacedName(node) { + this.visit(node.namespace); + this.visit(node.name); + } +} + +/* vim: set sw=4 ts=4 et tw=80 : */ + +const version = "8.4.0"; + +/* + Copyright (C) 2012-2014 Yusuke Suzuki + Copyright (C) 2013 Alex Seville + Copyright (C) 2014 Thiago de Arruda + + 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. + + 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 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. +*/ + +/** + * Set the default options + * @returns {Object} options + */ +function defaultOptions() { + return { + optimistic: false, + nodejsScope: false, + impliedStrict: false, + sourceType: "script", // one of ['script', 'module', 'commonjs'] + ecmaVersion: 5, + childVisitorKeys: null, + fallback: "iteration" + }; +} + +/** + * Preform deep update on option object + * @param {Object} target Options + * @param {Object} override Updates + * @returns {Object} Updated options + */ +function updateDeeply(target, override) { + + /** + * Is hash object + * @param {Object} value Test value + * @returns {boolean} Result + */ + function isHashObject(value) { + return typeof value === "object" && value instanceof Object && !(value instanceof Array) && !(value instanceof RegExp); + } + + for (const key in override) { + if (Object.hasOwn(override, key)) { + const val = override[key]; + + if (isHashObject(val)) { + if (isHashObject(target[key])) { + updateDeeply(target[key], val); + } else { + target[key] = updateDeeply({}, val); + } + } else { + target[key] = val; + } + } + } + return target; +} + +/** + * Main interface function. Takes an Espree syntax tree and returns the + * analyzed scopes. + * @function analyze + * @param {espree.Tree} tree Abstract Syntax Tree + * @param {Object} providedOptions Options that tailor the scope analysis + * @param {boolean} [providedOptions.optimistic=false] the optimistic flag + * @param {boolean} [providedOptions.ignoreEval=false] whether to check 'eval()' calls + * @param {boolean} [providedOptions.nodejsScope=false] whether the whole + * script is executed under node.js environment. When enabled, escope adds + * a function scope immediately following the global scope. + * @param {boolean} [providedOptions.impliedStrict=false] implied strict mode + * (if ecmaVersion >= 5). + * @param {string} [providedOptions.sourceType='script'] the source type of the script. one of 'script', 'module', and 'commonjs' + * @param {number} [providedOptions.ecmaVersion=5] which ECMAScript version is considered + * @param {boolean} [providedOptions.jsx=false] support JSX references + * @param {Object} [providedOptions.childVisitorKeys=null] Additional known visitor keys. See [esrecurse](https://github.com/estools/esrecurse)'s the `childVisitorKeys` option. + * @param {string} [providedOptions.fallback='iteration'] A kind of the fallback in order to encounter with unknown node. See [esrecurse](https://github.com/estools/esrecurse)'s the `fallback` option. + * @returns {ScopeManager} ScopeManager + */ +function analyze(tree, providedOptions) { + const options = updateDeeply(defaultOptions(), providedOptions); + const scopeManager = new ScopeManager(options); + const referencer = new Referencer(options, scopeManager); + + referencer.visit(tree); + + assert(scopeManager.__currentScope === null, "currentScope should be null."); + + return scopeManager; +} + +/* vim: set sw=4 ts=4 et tw=80 : */ + +exports.Definition = Definition; +exports.PatternVisitor = PatternVisitor; +exports.Reference = Reference; +exports.Referencer = Referencer; +exports.Scope = Scope; +exports.ScopeManager = ScopeManager; +exports.Variable = Variable; +exports.analyze = analyze; +exports.version = version; +//# sourceMappingURL=eslint-scope.cjs.map diff --git a/node_modules/eslint-scope/lib/assert.js b/node_modules/eslint-scope/lib/assert.js new file mode 100644 index 0000000000000000000000000000000000000000..6300bce7e85d91b2bd2a75a15dcbfa25a53e0d4f --- /dev/null +++ b/node_modules/eslint-scope/lib/assert.js @@ -0,0 +1,17 @@ +/** + * @fileoverview Assertion utilities. + * @author Nicholas C. Zakas + */ + +/** + * Throws an error if the given condition is not truthy. + * @param {boolean} condition The condition to check. + * @param {string} message The message to include with the error. + * @returns {void} + * @throws {Error} When the condition is not truthy. + */ +export function assert(condition, message = "Assertion failed.") { + if (!condition) { + throw new Error(message); + } +} diff --git a/node_modules/eslint-scope/lib/definition.js b/node_modules/eslint-scope/lib/definition.js new file mode 100644 index 0000000000000000000000000000000000000000..9744ef48b8f096b85f0d1924ffe3ade0febb2307 --- /dev/null +++ b/node_modules/eslint-scope/lib/definition.js @@ -0,0 +1,85 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ + +import Variable from "./variable.js"; + +/** + * @constructor Definition + */ +class Definition { + constructor(type, name, node, parent, index, kind) { + + /** + * @member {string} Definition#type - type of the occurrence (e.g. "Parameter", "Variable", ...). + */ + this.type = type; + + /** + * @member {espree.Identifier} Definition#name - the identifier AST node of the occurrence. + */ + this.name = name; + + /** + * @member {espree.Node} Definition#node - the enclosing node of the identifier. + */ + this.node = node; + + /** + * @member {espree.Node?} Definition#parent - the enclosing statement node of the identifier. + */ + this.parent = parent; + + /** + * @member {number?} Definition#index - the index in the declaration statement. + */ + this.index = index; + + /** + * @member {string?} Definition#kind - the kind of the declaration statement. + */ + this.kind = kind; + } +} + +/** + * @constructor ParameterDefinition + */ +class ParameterDefinition extends Definition { + constructor(name, node, index, rest) { + super(Variable.Parameter, name, node, null, index, null); + + /** + * Whether the parameter definition is a part of a rest parameter. + * @member {boolean} ParameterDefinition#rest + */ + this.rest = rest; + } +} + +export { + ParameterDefinition, + Definition +}; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/index.js b/node_modules/eslint-scope/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..85f8b510f0ade4bccdcce7335e1aa30ff223d14b --- /dev/null +++ b/node_modules/eslint-scope/lib/index.js @@ -0,0 +1,170 @@ +/* + Copyright (C) 2012-2014 Yusuke Suzuki + Copyright (C) 2013 Alex Seville + Copyright (C) 2014 Thiago de Arruda + + 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. + + 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 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. +*/ + +/** + * Escope (escope) is an ECMAScript + * scope analyzer extracted from the esmangle project. + *

+ * escope finds lexical scopes in a source program, i.e. areas of that + * program where different occurrences of the same identifier refer to the same + * variable. With each scope the contained variables are collected, and each + * identifier reference in code is linked to its corresponding variable (if + * possible). + *

+ * escope works on a syntax tree of the parsed source code which has + * to adhere to the + * Mozilla Parser API. E.g. espree is a parser + * that produces such syntax trees. + *

+ * The main interface is the {@link analyze} function. + * @module escope + */ + +import { assert } from "./assert.js"; + +import ScopeManager from "./scope-manager.js"; +import Referencer from "./referencer.js"; +import Reference from "./reference.js"; +import Variable from "./variable.js"; + +import eslintScopeVersion from "./version.js"; + +/** + * Set the default options + * @returns {Object} options + */ +function defaultOptions() { + return { + optimistic: false, + nodejsScope: false, + impliedStrict: false, + sourceType: "script", // one of ['script', 'module', 'commonjs'] + ecmaVersion: 5, + childVisitorKeys: null, + fallback: "iteration" + }; +} + +/** + * Preform deep update on option object + * @param {Object} target Options + * @param {Object} override Updates + * @returns {Object} Updated options + */ +function updateDeeply(target, override) { + + /** + * Is hash object + * @param {Object} value Test value + * @returns {boolean} Result + */ + function isHashObject(value) { + return typeof value === "object" && value instanceof Object && !(value instanceof Array) && !(value instanceof RegExp); + } + + for (const key in override) { + if (Object.hasOwn(override, key)) { + const val = override[key]; + + if (isHashObject(val)) { + if (isHashObject(target[key])) { + updateDeeply(target[key], val); + } else { + target[key] = updateDeeply({}, val); + } + } else { + target[key] = val; + } + } + } + return target; +} + +/** + * Main interface function. Takes an Espree syntax tree and returns the + * analyzed scopes. + * @function analyze + * @param {espree.Tree} tree Abstract Syntax Tree + * @param {Object} providedOptions Options that tailor the scope analysis + * @param {boolean} [providedOptions.optimistic=false] the optimistic flag + * @param {boolean} [providedOptions.ignoreEval=false] whether to check 'eval()' calls + * @param {boolean} [providedOptions.nodejsScope=false] whether the whole + * script is executed under node.js environment. When enabled, escope adds + * a function scope immediately following the global scope. + * @param {boolean} [providedOptions.impliedStrict=false] implied strict mode + * (if ecmaVersion >= 5). + * @param {string} [providedOptions.sourceType='script'] the source type of the script. one of 'script', 'module', and 'commonjs' + * @param {number} [providedOptions.ecmaVersion=5] which ECMAScript version is considered + * @param {boolean} [providedOptions.jsx=false] support JSX references + * @param {Object} [providedOptions.childVisitorKeys=null] Additional known visitor keys. See [esrecurse](https://github.com/estools/esrecurse)'s the `childVisitorKeys` option. + * @param {string} [providedOptions.fallback='iteration'] A kind of the fallback in order to encounter with unknown node. See [esrecurse](https://github.com/estools/esrecurse)'s the `fallback` option. + * @returns {ScopeManager} ScopeManager + */ +function analyze(tree, providedOptions) { + const options = updateDeeply(defaultOptions(), providedOptions); + const scopeManager = new ScopeManager(options); + const referencer = new Referencer(options, scopeManager); + + referencer.visit(tree); + + assert(scopeManager.__currentScope === null, "currentScope should be null."); + + return scopeManager; +} + +export { + + /** @name module:escope.version */ + eslintScopeVersion as version, + + /** @name module:escope.Reference */ + Reference, + + /** @name module:escope.Variable */ + Variable, + + /** @name module:escope.ScopeManager */ + ScopeManager, + + /** @name module:escope.Referencer */ + Referencer, + + analyze +}; + +/** @name module:escope.Definition */ +export { Definition } from "./definition.js"; + +/** @name module:escope.PatternVisitor */ +export { default as PatternVisitor } from "./pattern-visitor.js"; + +/** @name module:escope.Scope */ +export { Scope } from "./scope.js"; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/pattern-visitor.js b/node_modules/eslint-scope/lib/pattern-visitor.js new file mode 100644 index 0000000000000000000000000000000000000000..367a3773cf4ec36f007d9a5987b7e171f7e6b1b9 --- /dev/null +++ b/node_modules/eslint-scope/lib/pattern-visitor.js @@ -0,0 +1,154 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ + +import estraverse from "estraverse"; +import esrecurse from "esrecurse"; + +const { Syntax } = estraverse; + +/** + * Get last array element + * @param {Array} xs array + * @returns {any} Last elment + */ +function getLast(xs) { + return xs.at(-1) || null; +} + +/** + * Visitor for destructuring patterns. + */ +class PatternVisitor extends esrecurse.Visitor { + static isPattern(node) { + const nodeType = node.type; + + return ( + nodeType === Syntax.Identifier || + nodeType === Syntax.ObjectPattern || + nodeType === Syntax.ArrayPattern || + nodeType === Syntax.SpreadElement || + nodeType === Syntax.RestElement || + nodeType === Syntax.AssignmentPattern + ); + } + + constructor(options, rootPattern, callback) { + super(null, options); + this.rootPattern = rootPattern; + this.callback = callback; + this.assignments = []; + this.rightHandNodes = []; + this.restElements = []; + } + + Identifier(pattern) { + const lastRestElement = getLast(this.restElements); + + this.callback(pattern, { + topLevel: pattern === this.rootPattern, + rest: lastRestElement !== null && lastRestElement !== void 0 && lastRestElement.argument === pattern, + assignments: this.assignments + }); + } + + Property(property) { + + // Computed property's key is a right hand node. + if (property.computed) { + this.rightHandNodes.push(property.key); + } + + // If it's shorthand, its key is same as its value. + // If it's shorthand and has its default value, its key is same as its value.left (the value is AssignmentPattern). + // If it's not shorthand, the name of new variable is its value's. + this.visit(property.value); + } + + ArrayPattern(pattern) { + for (let i = 0, iz = pattern.elements.length; i < iz; ++i) { + const element = pattern.elements[i]; + + this.visit(element); + } + } + + AssignmentPattern(pattern) { + this.assignments.push(pattern); + this.visit(pattern.left); + this.rightHandNodes.push(pattern.right); + this.assignments.pop(); + } + + RestElement(pattern) { + this.restElements.push(pattern); + this.visit(pattern.argument); + this.restElements.pop(); + } + + MemberExpression(node) { + + // Computed property's key is a right hand node. + if (node.computed) { + this.rightHandNodes.push(node.property); + } + + // the object is only read, write to its property. + this.rightHandNodes.push(node.object); + } + + // + // ForInStatement.left and AssignmentExpression.left are LeftHandSideExpression. + // By spec, LeftHandSideExpression is Pattern or MemberExpression. + // (see also: https://github.com/estree/estree/pull/20#issuecomment-74584758) + // But espree 2.0 parses to ArrayExpression, ObjectExpression, etc... + // + + SpreadElement(node) { + this.visit(node.argument); + } + + ArrayExpression(node) { + node.elements.forEach(this.visit, this); + } + + AssignmentExpression(node) { + this.assignments.push(node); + this.visit(node.left); + this.rightHandNodes.push(node.right); + this.assignments.pop(); + } + + CallExpression(node) { + + // arguments are right hand nodes. + node.arguments.forEach(a => { + this.rightHandNodes.push(a); + }); + this.visit(node.callee); + } +} + +export default PatternVisitor; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/reference.js b/node_modules/eslint-scope/lib/reference.js new file mode 100644 index 0000000000000000000000000000000000000000..e657d628649cc9ea13bc7f8b6c6195e12c0f4344 --- /dev/null +++ b/node_modules/eslint-scope/lib/reference.js @@ -0,0 +1,166 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ + +const READ = 0x1; +const WRITE = 0x2; +const RW = READ | WRITE; + +/** + * A Reference represents a single occurrence of an identifier in code. + * @constructor Reference + */ +class Reference { + constructor(ident, scope, flag, writeExpr, maybeImplicitGlobal, partial, init) { + + /** + * Identifier syntax node. + * @member {espreeIdentifier} Reference#identifier + */ + this.identifier = ident; + + /** + * Reference to the enclosing Scope. + * @member {Scope} Reference#from + */ + this.from = scope; + + /** + * Whether the reference comes from a dynamic scope (such as 'eval', + * 'with', etc.), and may be trapped by dynamic scopes. + * @member {boolean} Reference#tainted + */ + this.tainted = false; + + /** + * The variable this reference is resolved with. + * @member {Variable} Reference#resolved + */ + this.resolved = null; + + /** + * The read-write mode of the reference. (Value is one of {@link + * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}). + * @member {number} Reference#flag + * @private + */ + this.flag = flag; + if (this.isWrite()) { + + /** + * If reference is writeable, this is the tree being written to it. + * @member {espreeNode} Reference#writeExpr + */ + this.writeExpr = writeExpr; + + /** + * Whether the Reference might refer to a partial value of writeExpr. + * @member {boolean} Reference#partial + */ + this.partial = partial; + + /** + * Whether the Reference is to write of initialization. + * @member {boolean} Reference#init + */ + this.init = init; + } + this.__maybeImplicitGlobal = maybeImplicitGlobal; + } + + /** + * Whether the reference is static. + * @function Reference#isStatic + * @returns {boolean} static + */ + isStatic() { + return !this.tainted && this.resolved && this.resolved.scope.isStatic(); + } + + /** + * Whether the reference is writeable. + * @function Reference#isWrite + * @returns {boolean} write + */ + isWrite() { + return !!(this.flag & Reference.WRITE); + } + + /** + * Whether the reference is readable. + * @function Reference#isRead + * @returns {boolean} read + */ + isRead() { + return !!(this.flag & Reference.READ); + } + + /** + * Whether the reference is read-only. + * @function Reference#isReadOnly + * @returns {boolean} read only + */ + isReadOnly() { + return this.flag === Reference.READ; + } + + /** + * Whether the reference is write-only. + * @function Reference#isWriteOnly + * @returns {boolean} write only + */ + isWriteOnly() { + return this.flag === Reference.WRITE; + } + + /** + * Whether the reference is read-write. + * @function Reference#isReadWrite + * @returns {boolean} read write + */ + isReadWrite() { + return this.flag === Reference.RW; + } +} + +/** + * @constant Reference.READ + * @private + */ +Reference.READ = READ; + +/** + * @constant Reference.WRITE + * @private + */ +Reference.WRITE = WRITE; + +/** + * @constant Reference.RW + * @private + */ +Reference.RW = RW; + +export default Reference; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/referencer.js b/node_modules/eslint-scope/lib/referencer.js new file mode 100644 index 0000000000000000000000000000000000000000..ad88ea20de184889c5de33ec63f3d6dd665ce7d0 --- /dev/null +++ b/node_modules/eslint-scope/lib/referencer.js @@ -0,0 +1,708 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ + +import estraverse from "estraverse"; +import esrecurse from "esrecurse"; +import Reference from "./reference.js"; +import Variable from "./variable.js"; +import PatternVisitor from "./pattern-visitor.js"; +import { Definition, ParameterDefinition } from "./definition.js"; +import { assert } from "./assert.js"; + +const { Syntax } = estraverse; + +/** + * Traverse identifier in pattern + * @param {Object} options options + * @param {pattern} rootPattern root pattern + * @param {Refencer} referencer referencer + * @param {callback} callback callback + * @returns {void} + */ +function traverseIdentifierInPattern(options, rootPattern, referencer, callback) { + + // Call the callback at left hand identifier nodes, and Collect right hand nodes. + const visitor = new PatternVisitor(options, rootPattern, callback); + + visitor.visit(rootPattern); + + // Process the right hand nodes recursively. + if (referencer !== null && referencer !== void 0) { + visitor.rightHandNodes.forEach(referencer.visit, referencer); + } +} + +// Importing ImportDeclaration. +// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-moduledeclarationinstantiation +// https://github.com/estree/estree/blob/master/es6.md#importdeclaration +// FIXME: Now, we don't create module environment, because the context is +// implementation dependent. + +/** + * Visitor for import specifiers. + */ +class Importer extends esrecurse.Visitor { + constructor(declaration, referencer) { + super(null, referencer.options); + this.declaration = declaration; + this.referencer = referencer; + } + + visitImport(id, specifier) { + this.referencer.visitPattern(id, pattern => { + this.referencer.currentScope().__define(pattern, + new Definition( + Variable.ImportBinding, + pattern, + specifier, + this.declaration, + null, + null + )); + }); + } + + ImportNamespaceSpecifier(node) { + const local = (node.local || node.id); + + if (local) { + this.visitImport(local, node); + } + } + + ImportDefaultSpecifier(node) { + const local = (node.local || node.id); + + this.visitImport(local, node); + } + + ImportSpecifier(node) { + const local = (node.local || node.id); + + if (node.name) { + this.visitImport(node.name, node); + } else { + this.visitImport(local, node); + } + } +} + +/** + * Referencing variables and creating bindings. + */ +class Referencer extends esrecurse.Visitor { + constructor(options, scopeManager) { + super(null, options); + this.options = options; + this.scopeManager = scopeManager; + this.parent = null; + this.isInnerMethodDefinition = false; + } + + currentScope() { + return this.scopeManager.__currentScope; + } + + close(node) { + while (this.currentScope() && node === this.currentScope().block) { + this.scopeManager.__currentScope = this.currentScope().__close(this.scopeManager); + } + } + + pushInnerMethodDefinition(isInnerMethodDefinition) { + const previous = this.isInnerMethodDefinition; + + this.isInnerMethodDefinition = isInnerMethodDefinition; + return previous; + } + + popInnerMethodDefinition(isInnerMethodDefinition) { + this.isInnerMethodDefinition = isInnerMethodDefinition; + } + + referencingDefaultValue(pattern, assignments, maybeImplicitGlobal, init) { + const scope = this.currentScope(); + + assignments.forEach(assignment => { + scope.__referencing( + pattern, + Reference.WRITE, + assignment.right, + maybeImplicitGlobal, + pattern !== assignment.left, + init + ); + }); + } + + visitPattern(node, options, callback) { + let visitPatternOptions = options; + let visitPatternCallback = callback; + + if (typeof options === "function") { + visitPatternCallback = options; + visitPatternOptions = { processRightHandNodes: false }; + } + + traverseIdentifierInPattern( + this.options, + node, + visitPatternOptions.processRightHandNodes ? this : null, + visitPatternCallback + ); + } + + visitFunction(node) { + let i, iz; + + // FunctionDeclaration name is defined in upper scope + // NOTE: Not referring variableScope. It is intended. + // Since + // in ES5, FunctionDeclaration should be in FunctionBody. + // in ES6, FunctionDeclaration should be block scoped. + + if (node.type === Syntax.FunctionDeclaration) { + + // id is defined in upper scope + this.currentScope().__define(node.id, + new Definition( + Variable.FunctionName, + node.id, + node, + null, + null, + null + )); + } + + // FunctionExpression with name creates its special scope; + // FunctionExpressionNameScope. + if (node.type === Syntax.FunctionExpression && node.id) { + this.scopeManager.__nestFunctionExpressionNameScope(node); + } + + // Consider this function is in the MethodDefinition. + this.scopeManager.__nestFunctionScope(node, this.isInnerMethodDefinition); + + const that = this; + + /** + * Visit pattern callback + * @param {pattern} pattern pattern + * @param {Object} info info + * @returns {void} + */ + function visitPatternCallback(pattern, info) { + that.currentScope().__define(pattern, + new ParameterDefinition( + pattern, + node, + i, + info.rest + )); + + that.referencingDefaultValue(pattern, info.assignments, null, true); + } + + // Process parameter declarations. + for (i = 0, iz = node.params.length; i < iz; ++i) { + this.visitPattern(node.params[i], { processRightHandNodes: true }, visitPatternCallback); + } + + // if there's a rest argument, add that + if (node.rest) { + this.visitPattern({ + type: "RestElement", + argument: node.rest + }, pattern => { + this.currentScope().__define(pattern, + new ParameterDefinition( + pattern, + node, + node.params.length, + true + )); + }); + } + + // In TypeScript there are a number of function-like constructs which have no body, + // so check it exists before traversing + if (node.body) { + + // Skip BlockStatement to prevent creating BlockStatement scope. + if (node.body.type === Syntax.BlockStatement) { + this.visitChildren(node.body); + } else { + this.visit(node.body); + } + } + + this.close(node); + } + + visitClass(node) { + if (node.type === Syntax.ClassDeclaration) { + this.currentScope().__define(node.id, + new Definition( + Variable.ClassName, + node.id, + node, + null, + null, + null + )); + } + + this.scopeManager.__nestClassScope(node); + + if (node.id) { + this.currentScope().__define(node.id, + new Definition( + Variable.ClassName, + node.id, + node + )); + } + + this.visit(node.superClass); + this.visit(node.body); + + this.close(node); + } + + visitProperty(node) { + let previous; + + if (node.computed) { + this.visit(node.key); + } + + const isMethodDefinition = node.type === Syntax.MethodDefinition; + + if (isMethodDefinition) { + previous = this.pushInnerMethodDefinition(true); + } + this.visit(node.value); + if (isMethodDefinition) { + this.popInnerMethodDefinition(previous); + } + } + + visitForIn(node) { + if (node.left.type === Syntax.VariableDeclaration && node.left.kind !== "var") { + this.scopeManager.__nestForScope(node); + } + + if (node.left.type === Syntax.VariableDeclaration) { + this.visit(node.left); + this.visitPattern(node.left.declarations[0].id, pattern => { + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, null, true, true); + }); + } else { + this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => { + let maybeImplicitGlobal = null; + + if (!this.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern, + node + }; + } + this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, true, false); + }); + } + this.visit(node.right); + this.visit(node.body); + + this.close(node); + } + + visitVariableDeclaration(variableTargetScope, type, node, index) { + + const decl = node.declarations[index]; + const init = decl.init; + + this.visitPattern(decl.id, { processRightHandNodes: true }, (pattern, info) => { + variableTargetScope.__define( + pattern, + new Definition( + type, + pattern, + decl, + node, + index, + node.kind + ) + ); + + this.referencingDefaultValue(pattern, info.assignments, null, true); + if (init) { + this.currentScope().__referencing(pattern, Reference.WRITE, init, null, !info.topLevel, true); + } + }); + } + + AssignmentExpression(node) { + if (PatternVisitor.isPattern(node.left)) { + if (node.operator === "=") { + this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => { + let maybeImplicitGlobal = null; + + if (!this.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern, + node + }; + } + this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, !info.topLevel, false); + }); + } else { + this.currentScope().__referencing(node.left, Reference.RW, node.right); + } + } else { + this.visit(node.left); + } + this.visit(node.right); + } + + CatchClause(node) { + this.scopeManager.__nestCatchScope(node); + + this.visitPattern(node.param, { processRightHandNodes: true }, (pattern, info) => { + this.currentScope().__define(pattern, + new Definition( + Variable.CatchClause, + pattern, + node, + null, + null, + null + )); + this.referencingDefaultValue(pattern, info.assignments, null, true); + }); + this.visit(node.body); + + this.close(node); + } + + Program(node) { + this.scopeManager.__nestGlobalScope(node); + + if (this.scopeManager.isGlobalReturn()) { + + // Force strictness of GlobalScope to false when using node.js scope. + this.currentScope().isStrict = false; + this.scopeManager.__nestFunctionScope(node, false); + } + + if (this.scopeManager.__isES6() && this.scopeManager.isModule()) { + this.scopeManager.__nestModuleScope(node); + } + + if (this.scopeManager.isStrictModeSupported() && this.scopeManager.isImpliedStrict()) { + this.currentScope().isStrict = true; + } + + this.visitChildren(node); + this.close(node); + } + + Identifier(node) { + this.currentScope().__referencing(node); + } + + // eslint-disable-next-line class-methods-use-this -- Desired as instance method + PrivateIdentifier() { + + // Do nothing. + } + + UpdateExpression(node) { + if (PatternVisitor.isPattern(node.argument)) { + this.currentScope().__referencing(node.argument, Reference.RW, null); + } else { + this.visitChildren(node); + } + } + + MemberExpression(node) { + this.visit(node.object); + if (node.computed) { + this.visit(node.property); + } + } + + Property(node) { + this.visitProperty(node); + } + + PropertyDefinition(node) { + const { computed, key, value } = node; + + if (computed) { + this.visit(key); + } + if (value) { + this.scopeManager.__nestClassFieldInitializerScope(value); + this.visit(value); + this.close(value); + } + } + + StaticBlock(node) { + this.scopeManager.__nestClassStaticBlockScope(node); + + this.visitChildren(node); + + this.close(node); + } + + MethodDefinition(node) { + this.visitProperty(node); + } + + BreakStatement() {} // eslint-disable-line class-methods-use-this -- Desired as instance method + + ContinueStatement() {} // eslint-disable-line class-methods-use-this -- Desired as instance method + + LabeledStatement(node) { + this.visit(node.body); + } + + ForStatement(node) { + + // Create ForStatement declaration. + // NOTE: In ES6, ForStatement dynamically generates + // per iteration environment. However, escope is + // a static analyzer, we only generate one scope for ForStatement. + if (node.init && node.init.type === Syntax.VariableDeclaration && node.init.kind !== "var") { + this.scopeManager.__nestForScope(node); + } + + this.visitChildren(node); + + this.close(node); + } + + ClassExpression(node) { + this.visitClass(node); + } + + ClassDeclaration(node) { + this.visitClass(node); + } + + CallExpression(node) { + + // Check this is direct call to eval + if (!this.scopeManager.__ignoreEval() && node.callee.type === Syntax.Identifier && node.callee.name === "eval") { + + // NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and + // let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment. + this.currentScope().variableScope.__detectEval(); + } + this.visitChildren(node); + } + + BlockStatement(node) { + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestBlockScope(node); + } + + this.visitChildren(node); + + this.close(node); + } + + ThisExpression() { + this.currentScope().variableScope.__detectThis(); + } + + WithStatement(node) { + this.visit(node.object); + + // Then nest scope for WithStatement. + this.scopeManager.__nestWithScope(node); + + this.visit(node.body); + + this.close(node); + } + + VariableDeclaration(node) { + const variableTargetScope = (node.kind === "var") ? this.currentScope().variableScope : this.currentScope(); + + for (let i = 0, iz = node.declarations.length; i < iz; ++i) { + const decl = node.declarations[i]; + + this.visitVariableDeclaration(variableTargetScope, Variable.Variable, node, i); + if (decl.init) { + this.visit(decl.init); + } + } + } + + // sec 13.11.8 + SwitchStatement(node) { + this.visit(node.discriminant); + + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestSwitchScope(node); + } + + for (let i = 0, iz = node.cases.length; i < iz; ++i) { + this.visit(node.cases[i]); + } + + this.close(node); + } + + FunctionDeclaration(node) { + this.visitFunction(node); + } + + FunctionExpression(node) { + this.visitFunction(node); + } + + ForOfStatement(node) { + this.visitForIn(node); + } + + ForInStatement(node) { + this.visitForIn(node); + } + + ArrowFunctionExpression(node) { + this.visitFunction(node); + } + + ImportDeclaration(node) { + assert(this.scopeManager.__isES6() && this.scopeManager.isModule(), "ImportDeclaration should appear when the mode is ES6 and in the module context."); + + const importer = new Importer(node, this); + + importer.visit(node); + } + + visitExportDeclaration(node) { + if (node.source) { + return; + } + if (node.declaration) { + this.visit(node.declaration); + return; + } + + this.visitChildren(node); + } + + // TODO: ExportDeclaration doesn't exist. for bc? + ExportDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportAllDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportDefaultDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportNamedDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportSpecifier(node) { + + // TODO: `node.id` doesn't exist. for bc? + const local = (node.id || node.local); + + this.visit(local); + } + + MetaProperty() { // eslint-disable-line class-methods-use-this -- Desired as instance method + + // do nothing. + } + + JSXIdentifier(node) { + + // Special case: "this" should not count as a reference + if (this.scopeManager.__isJSXEnabled() && node.name !== "this") { + this.currentScope().__referencing(node); + } + } + + JSXMemberExpression(node) { + this.visit(node.object); + } + + JSXElement(node) { + if (this.scopeManager.__isJSXEnabled()) { + this.visit(node.openingElement); + node.children.forEach(this.visit, this); + } else { + this.visitChildren(node); + } + } + + JSXOpeningElement(node) { + if (this.scopeManager.__isJSXEnabled()) { + + const nameNode = node.name; + const isComponentName = nameNode.type === "JSXIdentifier" && nameNode.name[0].toUpperCase() === nameNode.name[0]; + const isComponent = isComponentName || nameNode.type === "JSXMemberExpression"; + + // we only want to visit JSXIdentifier nodes if they are capitalized + if (isComponent) { + this.visit(nameNode); + } + } + + node.attributes.forEach(this.visit, this); + } + + JSXAttribute(node) { + if (node.value) { + this.visit(node.value); + } + } + + JSXExpressionContainer(node) { + this.visit(node.expression); + } + + JSXNamespacedName(node) { + this.visit(node.namespace); + this.visit(node.name); + } +} + +export default Referencer; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/scope-manager.js b/node_modules/eslint-scope/lib/scope-manager.js new file mode 100644 index 0000000000000000000000000000000000000000..b012b646d18df5acee98fdc4f093556710c237be --- /dev/null +++ b/node_modules/eslint-scope/lib/scope-manager.js @@ -0,0 +1,253 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ + +import { + BlockScope, + CatchScope, + ClassFieldInitializerScope, + ClassStaticBlockScope, + ClassScope, + ForScope, + FunctionExpressionNameScope, + FunctionScope, + GlobalScope, + ModuleScope, + SwitchScope, + WithScope +} from "./scope.js"; +import { assert } from "./assert.js"; + +/** + * @constructor ScopeManager + */ +class ScopeManager { + constructor(options) { + this.scopes = []; + this.globalScope = null; + this.__nodeToScope = new WeakMap(); + this.__currentScope = null; + this.__options = options; + this.__declaredVariables = new WeakMap(); + } + + __isOptimistic() { + return this.__options.optimistic; + } + + __ignoreEval() { + return this.__options.ignoreEval; + } + + __isJSXEnabled() { + return this.__options.jsx === true; + } + + isGlobalReturn() { + return this.__options.nodejsScope || this.__options.sourceType === "commonjs"; + } + + isModule() { + return this.__options.sourceType === "module"; + } + + isImpliedStrict() { + return this.__options.impliedStrict; + } + + isStrictModeSupported() { + return this.__options.ecmaVersion >= 5; + } + + // Returns appropriate scope for this node. + __get(node) { + return this.__nodeToScope.get(node); + } + + /** + * Get variables that are declared by the node. + * + * "are declared by the node" means the node is same as `Variable.defs[].node` or `Variable.defs[].parent`. + * If the node declares nothing, this method returns an empty array. + * CAUTION: This API is experimental. See https://github.com/estools/escope/pull/69 for more details. + * @param {Espree.Node} node a node to get. + * @returns {Variable[]} variables that declared by the node. + */ + getDeclaredVariables(node) { + return this.__declaredVariables.get(node) || []; + } + + /** + * acquire scope from node. + * @function ScopeManager#acquire + * @param {Espree.Node} node node for the acquired scope. + * @param {?boolean} [inner=false] look up the most inner scope, default value is false. + * @returns {Scope?} Scope from node + */ + acquire(node, inner) { + + /** + * predicate + * @param {Scope} testScope scope to test + * @returns {boolean} predicate + */ + function predicate(testScope) { + if (testScope.type === "function" && testScope.functionExpressionScope) { + return false; + } + return true; + } + + const scopes = this.__get(node); + + if (!scopes || scopes.length === 0) { + return null; + } + + // Heuristic selection from all scopes. + // If you would like to get all scopes, please use ScopeManager#acquireAll. + if (scopes.length === 1) { + return scopes[0]; + } + + if (inner) { + for (let i = scopes.length - 1; i >= 0; --i) { + const scope = scopes[i]; + + if (predicate(scope)) { + return scope; + } + } + } else { + for (let i = 0, iz = scopes.length; i < iz; ++i) { + const scope = scopes[i]; + + if (predicate(scope)) { + return scope; + } + } + } + + return null; + } + + /** + * acquire all scopes from node. + * @function ScopeManager#acquireAll + * @param {Espree.Node} node node for the acquired scope. + * @returns {Scopes?} Scope array + */ + acquireAll(node) { + return this.__get(node); + } + + /** + * release the node. + * @function ScopeManager#release + * @param {Espree.Node} node releasing node. + * @param {?boolean} [inner=false] look up the most inner scope, default value is false. + * @returns {Scope?} upper scope for the node. + */ + release(node, inner) { + const scopes = this.__get(node); + + if (scopes && scopes.length) { + const scope = scopes[0].upper; + + if (!scope) { + return null; + } + return this.acquire(scope.block, inner); + } + return null; + } + + attach() { } // eslint-disable-line class-methods-use-this -- Desired as instance method + + detach() { } // eslint-disable-line class-methods-use-this -- Desired as instance method + + __nestScope(scope) { + if (scope instanceof GlobalScope) { + assert(this.__currentScope === null); + this.globalScope = scope; + } + this.__currentScope = scope; + return scope; + } + + __nestGlobalScope(node) { + return this.__nestScope(new GlobalScope(this, node)); + } + + __nestBlockScope(node) { + return this.__nestScope(new BlockScope(this, this.__currentScope, node)); + } + + __nestFunctionScope(node, isMethodDefinition) { + return this.__nestScope(new FunctionScope(this, this.__currentScope, node, isMethodDefinition)); + } + + __nestForScope(node) { + return this.__nestScope(new ForScope(this, this.__currentScope, node)); + } + + __nestCatchScope(node) { + return this.__nestScope(new CatchScope(this, this.__currentScope, node)); + } + + __nestWithScope(node) { + return this.__nestScope(new WithScope(this, this.__currentScope, node)); + } + + __nestClassScope(node) { + return this.__nestScope(new ClassScope(this, this.__currentScope, node)); + } + + __nestClassFieldInitializerScope(node) { + return this.__nestScope(new ClassFieldInitializerScope(this, this.__currentScope, node)); + } + + __nestClassStaticBlockScope(node) { + return this.__nestScope(new ClassStaticBlockScope(this, this.__currentScope, node)); + } + + __nestSwitchScope(node) { + return this.__nestScope(new SwitchScope(this, this.__currentScope, node)); + } + + __nestModuleScope(node) { + return this.__nestScope(new ModuleScope(this, this.__currentScope, node)); + } + + __nestFunctionExpressionNameScope(node) { + return this.__nestScope(new FunctionExpressionNameScope(this, this.__currentScope, node)); + } + + __isES6() { + return this.__options.ecmaVersion >= 6; + } +} + +export default ScopeManager; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/scope.js b/node_modules/eslint-scope/lib/scope.js new file mode 100644 index 0000000000000000000000000000000000000000..46eeb7719505ddca5b5d6a77869e17874d3d8288 --- /dev/null +++ b/node_modules/eslint-scope/lib/scope.js @@ -0,0 +1,793 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ + +import estraverse from "estraverse"; + +import Reference from "./reference.js"; +import Variable from "./variable.js"; +import { Definition } from "./definition.js"; +import { assert } from "./assert.js"; + +const { Syntax } = estraverse; + +/** + * Test if scope is struct + * @param {Scope} scope scope + * @param {Block} block block + * @param {boolean} isMethodDefinition is method definition + * @returns {boolean} is strict scope + */ +function isStrictScope(scope, block, isMethodDefinition) { + let body; + + // When upper scope is exists and strict, inner scope is also strict. + if (scope.upper && scope.upper.isStrict) { + return true; + } + + if (isMethodDefinition) { + return true; + } + + if (scope.type === "class" || scope.type === "module") { + return true; + } + + if (scope.type === "block" || scope.type === "switch") { + return false; + } + + if (scope.type === "function") { + if (block.type === Syntax.ArrowFunctionExpression && block.body.type !== Syntax.BlockStatement) { + return false; + } + + if (block.type === Syntax.Program) { + body = block; + } else { + body = block.body; + } + + if (!body) { + return false; + } + } else if (scope.type === "global") { + body = block; + } else { + return false; + } + + // Search for a 'use strict' directive. + for (let i = 0, iz = body.body.length; i < iz; ++i) { + const stmt = body.body[i]; + + /* + * Check if the current statement is a directive. + * If it isn't, then we're past the directive prologue + * so stop the search because directives cannot + * appear after this point. + * + * Some parsers set `directive:null` on non-directive + * statements, so the `typeof` check is safer than + * checking for property existence. + */ + if (typeof stmt.directive !== "string") { + break; + } + + if (stmt.directive === "use strict") { + return true; + } + } + + return false; +} + +/** + * Register scope + * @param {ScopeManager} scopeManager scope manager + * @param {Scope} scope scope + * @returns {void} + */ +function registerScope(scopeManager, scope) { + scopeManager.scopes.push(scope); + + const scopes = scopeManager.__nodeToScope.get(scope.block); + + if (scopes) { + scopes.push(scope); + } else { + scopeManager.__nodeToScope.set(scope.block, [scope]); + } +} + +/** + * Should be statically + * @param {Object} def def + * @returns {boolean} should be statically + */ +function shouldBeStatically(def) { + return ( + (def.type === Variable.ClassName) || + (def.type === Variable.Variable && def.parent.kind !== "var") + ); +} + +/** + * @constructor Scope + */ +class Scope { + constructor(scopeManager, type, upperScope, block, isMethodDefinition) { + + /** + * One of "global", "module", "function", "function-expression-name", "block", "switch", "catch", "with", "for", + * "class", "class-field-initializer", "class-static-block". + * @member {string} Scope#type + */ + this.type = type; + + /** + * The scoped {@link Variable}s of this scope, as { Variable.name + * : Variable }. + * @member {Map} Scope#set + */ + this.set = new Map(); + + /** + * The tainted variables of this scope, as { Variable.name : + * boolean }. + * @member {Map} Scope#taints + */ + this.taints = new Map(); + + /** + * Generally, through the lexical scoping of JS you can always know + * which variable an identifier in the source code refers to. There are + * a few exceptions to this rule. With 'global' and 'with' scopes you + * can only decide at runtime which variable a reference refers to. + * Moreover, if 'eval()' is used in a scope, it might introduce new + * bindings in this or its parent scopes. + * All those scopes are considered 'dynamic'. + * @member {boolean} Scope#dynamic + */ + this.dynamic = this.type === "global" || this.type === "with"; + + /** + * A reference to the scope-defining syntax node. + * @member {espree.Node} Scope#block + */ + this.block = block; + + /** + * The {@link Reference|references} that are not resolved with this scope. + * @member {Reference[]} Scope#through + */ + this.through = []; + + /** + * The scoped {@link Variable}s of this scope. In the case of a + * 'function' scope this includes the automatic argument arguments as + * its first element, as well as all further formal arguments. + * @member {Variable[]} Scope#variables + */ + this.variables = []; + + /** + * Any variable {@link Reference|reference} found in this scope. This + * includes occurrences of local variables as well as variables from + * parent scopes (including the global scope). For local variables + * this also includes defining occurrences (like in a 'var' statement). + * In a 'function' scope this does not include the occurrences of the + * formal parameter in the parameter list. + * @member {Reference[]} Scope#references + */ + this.references = []; + + /** + * For 'global' and 'function' scopes, this is a self-reference. For + * other scope types this is the variableScope value of the + * parent scope. + * @member {Scope} Scope#variableScope + */ + this.variableScope = + this.type === "global" || + this.type === "module" || + this.type === "function" || + this.type === "class-field-initializer" || + this.type === "class-static-block" + ? this + : upperScope.variableScope; + + /** + * Whether this scope is created by a FunctionExpression. + * @member {boolean} Scope#functionExpressionScope + */ + this.functionExpressionScope = false; + + /** + * Whether this is a scope that contains an 'eval()' invocation. + * @member {boolean} Scope#directCallToEvalScope + */ + this.directCallToEvalScope = false; + + /** + * @member {boolean} Scope#thisFound + */ + this.thisFound = false; + + this.__left = []; + + /** + * Reference to the parent {@link Scope|scope}. + * @member {Scope} Scope#upper + */ + this.upper = upperScope; + + /** + * Whether 'use strict' is in effect in this scope. + * @member {boolean} Scope#isStrict + */ + this.isStrict = scopeManager.isStrictModeSupported() + ? isStrictScope(this, block, isMethodDefinition) + : false; + + /** + * List of nested {@link Scope}s. + * @member {Scope[]} Scope#childScopes + */ + this.childScopes = []; + if (this.upper) { + this.upper.childScopes.push(this); + } + + this.__declaredVariables = scopeManager.__declaredVariables; + + registerScope(scopeManager, this); + } + + __shouldStaticallyClose(scopeManager) { + return (!this.dynamic || scopeManager.__isOptimistic()); + } + + __shouldStaticallyCloseForGlobal(ref) { + + // On global scope, let/const/class declarations should be resolved statically. + const name = ref.identifier.name; + + if (!this.set.has(name)) { + return false; + } + + const variable = this.set.get(name); + const defs = variable.defs; + + return defs.length > 0 && defs.every(shouldBeStatically); + } + + __staticCloseRef(ref) { + if (!this.__resolve(ref)) { + this.__delegateToUpperScope(ref); + } + } + + __dynamicCloseRef(ref) { + + // notify all names are through to global + let current = this; + + do { + current.through.push(ref); + current = current.upper; + } while (current); + } + + __globalCloseRef(ref) { + + // let/const/class declarations should be resolved statically. + // others should be resolved dynamically. + if (this.__shouldStaticallyCloseForGlobal(ref)) { + this.__staticCloseRef(ref); + } else { + this.__dynamicCloseRef(ref); + } + } + + __close(scopeManager) { + let closeRef; + + if (this.__shouldStaticallyClose(scopeManager)) { + closeRef = this.__staticCloseRef; + } else if (this.type !== "global") { + closeRef = this.__dynamicCloseRef; + } else { + closeRef = this.__globalCloseRef; + } + + // Try Resolving all references in this scope. + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; + + closeRef.call(this, ref); + } + this.__left = null; + + return this.upper; + } + + // To override by function scopes. + // References in default parameters isn't resolved to variables which are in their function body. + __isValidResolution(ref, variable) { // eslint-disable-line class-methods-use-this, no-unused-vars -- Desired as instance method with signature + return true; + } + + __resolve(ref) { + const name = ref.identifier.name; + + if (!this.set.has(name)) { + return false; + } + const variable = this.set.get(name); + + if (!this.__isValidResolution(ref, variable)) { + return false; + } + variable.references.push(ref); + variable.stack = variable.stack && ref.from.variableScope === this.variableScope; + if (ref.tainted) { + variable.tainted = true; + this.taints.set(variable.name, true); + } + ref.resolved = variable; + + return true; + } + + __delegateToUpperScope(ref) { + if (this.upper) { + this.upper.__left.push(ref); + } + this.through.push(ref); + } + + __addDeclaredVariablesOfNode(variable, node) { + if (node === null || node === void 0) { + return; + } + + let variables = this.__declaredVariables.get(node); + + if (variables === null || variables === void 0) { + variables = []; + this.__declaredVariables.set(node, variables); + } + if (!variables.includes(variable)) { + variables.push(variable); + } + } + + __defineGeneric(name, set, variables, node, def) { + let variable; + + variable = set.get(name); + if (!variable) { + variable = new Variable(name, this); + set.set(name, variable); + variables.push(variable); + } + + if (def) { + variable.defs.push(def); + this.__addDeclaredVariablesOfNode(variable, def.node); + this.__addDeclaredVariablesOfNode(variable, def.parent); + } + if (node) { + variable.identifiers.push(node); + } + } + + __define(node, def) { + if (node && node.type === Syntax.Identifier) { + this.__defineGeneric( + node.name, + this.set, + this.variables, + node, + def + ); + } + } + + __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial, init) { + + // because Array element may be null + if (!node || (node.type !== Syntax.Identifier && node.type !== "JSXIdentifier")) { + return; + } + + // Specially handle like `this`. + if (node.name === "super") { + return; + } + + const ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial, !!init); + + this.references.push(ref); + this.__left.push(ref); + } + + __detectEval() { + let current = this; + + this.directCallToEvalScope = true; + do { + current.dynamic = true; + current = current.upper; + } while (current); + } + + __detectThis() { + this.thisFound = true; + } + + __isClosed() { + return this.__left === null; + } + + /** + * returns resolved {Reference} + * @function Scope#resolve + * @param {Espree.Identifier} ident identifier to be resolved. + * @returns {Reference} reference + */ + resolve(ident) { + let ref, i, iz; + + assert(this.__isClosed(), "Scope should be closed."); + assert(ident.type === Syntax.Identifier, "Target should be identifier."); + for (i = 0, iz = this.references.length; i < iz; ++i) { + ref = this.references[i]; + if (ref.identifier === ident) { + return ref; + } + } + return null; + } + + /** + * returns this scope is static + * @function Scope#isStatic + * @returns {boolean} static + */ + isStatic() { + return !this.dynamic; + } + + /** + * returns this scope has materialized arguments + * @function Scope#isArgumentsMaterialized + * @returns {boolean} arguemnts materialized + */ + isArgumentsMaterialized() { // eslint-disable-line class-methods-use-this -- Desired as instance method + return true; + } + + /** + * returns this scope has materialized `this` reference + * @function Scope#isThisMaterialized + * @returns {boolean} this materialized + */ + isThisMaterialized() { // eslint-disable-line class-methods-use-this -- Desired as instance method + return true; + } + + isUsedName(name) { + if (this.set.has(name)) { + return true; + } + for (let i = 0, iz = this.through.length; i < iz; ++i) { + if (this.through[i].identifier.name === name) { + return true; + } + } + return false; + } +} + +/** + * Global scope. + */ +class GlobalScope extends Scope { + constructor(scopeManager, block) { + super(scopeManager, "global", null, block, false); + this.implicit = { + set: new Map(), + variables: [], + + /** + * List of {@link Reference}s that are left to be resolved (i.e. which + * need to be linked to the variable they refer to). + * @member {Reference[]} Scope#implicit#left + */ + left: [] + }; + } + + __close(scopeManager) { + const implicit = []; + + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; + + if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) { + implicit.push(ref.__maybeImplicitGlobal); + } + } + + // create an implicit global variable from assignment expression + for (let i = 0, iz = implicit.length; i < iz; ++i) { + const info = implicit[i]; + + this.__defineImplicit(info.pattern, + new Definition( + Variable.ImplicitGlobalVariable, + info.pattern, + info.node, + null, + null, + null + )); + + } + + this.implicit.left = this.__left; + + return super.__close(scopeManager); + } + + __defineImplicit(node, def) { + if (node && node.type === Syntax.Identifier) { + this.__defineGeneric( + node.name, + this.implicit.set, + this.implicit.variables, + node, + def + ); + } + } +} + +/** + * Module scope. + */ +class ModuleScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "module", upperScope, block, false); + } +} + +/** + * Function expression name scope. + */ +class FunctionExpressionNameScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "function-expression-name", upperScope, block, false); + this.__define(block.id, + new Definition( + Variable.FunctionName, + block.id, + block, + null, + null, + null + )); + this.functionExpressionScope = true; + } +} + +/** + * Catch scope. + */ +class CatchScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "catch", upperScope, block, false); + } +} + +/** + * With statement scope. + */ +class WithScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "with", upperScope, block, false); + } + + __close(scopeManager) { + if (this.__shouldStaticallyClose(scopeManager)) { + return super.__close(scopeManager); + } + + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; + + ref.tainted = true; + this.__delegateToUpperScope(ref); + } + this.__left = null; + + return this.upper; + } +} + +/** + * Block scope. + */ +class BlockScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "block", upperScope, block, false); + } +} + +/** + * Switch scope. + */ +class SwitchScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "switch", upperScope, block, false); + } +} + +/** + * Function scope. + */ +class FunctionScope extends Scope { + constructor(scopeManager, upperScope, block, isMethodDefinition) { + super(scopeManager, "function", upperScope, block, isMethodDefinition); + + // section 9.2.13, FunctionDeclarationInstantiation. + // NOTE Arrow functions never have an arguments objects. + if (this.block.type !== Syntax.ArrowFunctionExpression) { + this.__defineArguments(); + } + } + + isArgumentsMaterialized() { + + // TODO(Constellation) + // We can more aggressive on this condition like this. + // + // function t() { + // // arguments of t is always hidden. + // function arguments() { + // } + // } + if (this.block.type === Syntax.ArrowFunctionExpression) { + return false; + } + + if (!this.isStatic()) { + return true; + } + + const variable = this.set.get("arguments"); + + assert(variable, "Always have arguments variable."); + return variable.tainted || variable.references.length !== 0; + } + + isThisMaterialized() { + if (!this.isStatic()) { + return true; + } + return this.thisFound; + } + + __defineArguments() { + this.__defineGeneric( + "arguments", + this.set, + this.variables, + null, + null + ); + this.taints.set("arguments", true); + } + + // References in default parameters isn't resolved to variables which are in their function body. + // const x = 1 + // function f(a = x) { // This `x` is resolved to the `x` in the outer scope. + // const x = 2 + // console.log(a) + // } + __isValidResolution(ref, variable) { + + // If `options.nodejsScope` is true, `this.block` becomes a Program node. + if (this.block.type === "Program") { + return true; + } + + const bodyStart = this.block.body.range[0]; + + // It's invalid resolution in the following case: + return !( + variable.scope === this && + ref.identifier.range[0] < bodyStart && // the reference is in the parameter part. + variable.defs.every(d => d.name.range[0] >= bodyStart) // the variable is in the body. + ); + } +} + +/** + * Scope of for, for-in, and for-of statements. + */ +class ForScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "for", upperScope, block, false); + } +} + +/** + * Class scope. + */ +class ClassScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "class", upperScope, block, false); + } +} + +/** + * Class field initializer scope. + */ +class ClassFieldInitializerScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "class-field-initializer", upperScope, block, true); + } +} + +/** + * Class static block scope. + */ +class ClassStaticBlockScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "class-static-block", upperScope, block, true); + } +} + +export { + Scope, + GlobalScope, + ModuleScope, + FunctionExpressionNameScope, + CatchScope, + WithScope, + BlockScope, + SwitchScope, + FunctionScope, + ForScope, + ClassScope, + ClassFieldInitializerScope, + ClassStaticBlockScope +}; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/variable.js b/node_modules/eslint-scope/lib/variable.js new file mode 100644 index 0000000000000000000000000000000000000000..286202f72a4abacbe3e941f9e3a461ae5775a7ec --- /dev/null +++ b/node_modules/eslint-scope/lib/variable.js @@ -0,0 +1,87 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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 Variable represents a locally scoped identifier. These include arguments to + * functions. + * @constructor Variable + */ +class Variable { + constructor(name, scope) { + + /** + * The variable name, as given in the source code. + * @member {string} Variable#name + */ + this.name = name; + + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as AST nodes. + * @member {espree.Identifier[]} Variable#identifiers + */ + this.identifiers = []; + + /** + * List of {@link Reference|references} of this variable (excluding parameter entries) + * in its defining scope and all nested scopes. For defining + * occurrences only see {@link Variable#defs}. + * @member {Reference[]} Variable#references + */ + this.references = []; + + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as custom objects. + * @member {Definition[]} Variable#defs + */ + this.defs = []; + + this.tainted = false; + + /** + * Whether this is a stack variable. + * @member {boolean} Variable#stack + */ + this.stack = true; + + /** + * Reference to the enclosing Scope. + * @member {Scope} Variable#scope + */ + this.scope = scope; + } +} + +Variable.CatchClause = "CatchClause"; +Variable.Parameter = "Parameter"; +Variable.FunctionName = "FunctionName"; +Variable.ClassName = "ClassName"; +Variable.Variable = "Variable"; +Variable.ImportBinding = "ImportBinding"; +Variable.ImplicitGlobalVariable = "ImplicitGlobalVariable"; + +export default Variable; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/eslint-scope/lib/version.js b/node_modules/eslint-scope/lib/version.js new file mode 100644 index 0000000000000000000000000000000000000000..fc36b2b888b111cc0e3c6b87df4b144cb890cdc3 --- /dev/null +++ b/node_modules/eslint-scope/lib/version.js @@ -0,0 +1,3 @@ +const version = "8.4.0"; + +export default version; diff --git a/node_modules/eslint-scope/package.json b/node_modules/eslint-scope/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e634e45bb9f88a30b678699d9a2742da67df3a58 --- /dev/null +++ b/node_modules/eslint-scope/package.json @@ -0,0 +1,64 @@ +{ + "name": "eslint-scope", + "description": "ECMAScript scope analyzer for ESLint", + "homepage": "https://github.com/eslint/js/blob/main/packages/eslint-scope/README.md", + "main": "./dist/eslint-scope.cjs", + "type": "module", + "exports": { + ".": { + "import": "./lib/index.js", + "require": "./dist/eslint-scope.cjs" + }, + "./package.json": "./package.json" + }, + "version": "8.4.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/eslint/js.git", + "directory": "packages/eslint-scope" + }, + "funding": "https://opencollective.com/eslint", + "keywords": [ + "eslint" + ], + "bugs": { + "url": "https://github.com/eslint/js/issues" + }, + "license": "BSD-2-Clause", + "scripts": { + "build": "rollup -c", + "build:update-version": "node tools/update-version.js", + "prepublishOnly": "npm run build:update-version && npm run build", + "pretest": "npm run build", + "release:generate:latest": "eslint-generate-release", + "release:generate:alpha": "eslint-generate-prerelease alpha", + "release:generate:beta": "eslint-generate-prerelease beta", + "release:generate:rc": "eslint-generate-prerelease rc", + "release:publish": "eslint-publish-release", + "test": "node Makefile.js test" + }, + "files": [ + "LICENSE", + "README.md", + "lib", + "dist/eslint-scope.cjs" + ], + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "devDependencies": { + "@typescript-eslint/parser": "^8.7.0", + "chai": "^4.3.4", + "eslint-release": "^3.2.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "npm-license": "^0.3.3", + "rollup": "^2.52.7", + "shelljs": "^0.8.5", + "typescript": "^5.4.2" + } +} diff --git a/node_modules/eslint-visitor-keys/LICENSE b/node_modules/eslint-visitor-keys/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..17a25538d9bd634bc079642d35d7a6422a0d850d --- /dev/null +++ b/node_modules/eslint-visitor-keys/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/eslint-visitor-keys/README.md b/node_modules/eslint-visitor-keys/README.md new file mode 100644 index 0000000000000000000000000000000000000000..aa860ba5774fe2d5b278c83be6b1acf24812799d --- /dev/null +++ b/node_modules/eslint-visitor-keys/README.md @@ -0,0 +1,121 @@ +# eslint-visitor-keys + +[![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys) +[![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys) +[![Build Status](https://github.com/eslint/js/workflows/CI/badge.svg)](https://github.com/eslint/js/actions) + +Constants and utilities about visitor keys to traverse AST. + +## 💿 Installation + +Use [npm] to install. + +```bash +$ npm install eslint-visitor-keys +``` + +### Requirements + +- [Node.js] `^18.18.0`, `^20.9.0`, or `>=21.1.0` + +## 📖 Usage + +To use in an ESM file: + +```js +import * as evk from "eslint-visitor-keys" +``` + +To use in a CommonJS file: + +```js +const evk = require("eslint-visitor-keys") +``` + +### evk.KEYS + +> type: `{ [type: string]: string[] | undefined }` + +Visitor keys. This keys are frozen. + +This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes. + +For example: + +``` +console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"] +``` + +### evk.getKeys(node) + +> type: `(node: object) => string[]` + +Get the visitor keys of a given AST node. + +This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`. + +This will be used to traverse unknown nodes. + +For example: + +```js +const node = { + type: "AssignmentExpression", + left: { type: "Identifier", name: "foo" }, + right: { type: "Literal", value: 0 } +} +console.log(evk.getKeys(node)) // → ["type", "left", "right"] +``` + +### evk.unionWith(additionalKeys) + +> type: `(additionalKeys: object) => { [type: string]: string[] | undefined }` + +Make the union set with `evk.KEYS` and the given keys. + +- The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that. +- It removes duplicated keys as keeping the first one. + +For example: + +```js +console.log(evk.unionWith({ + MethodDefinition: ["decorators"] +})) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... } +``` + +## 📰 Change log + +See [GitHub releases](https://github.com/eslint/js/releases). + +## 🍻 Contributing + +Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/). + +### Development commands + +- `npm test` runs tests and measures code coverage. +- `npm run lint` checks source codes with ESLint. +- `npm run test:open-coverage` opens the code coverage report of the previous test with your default browser. + +[npm]: https://www.npmjs.com/ +[Node.js]: https://nodejs.org/ +[ESTree]: https://github.com/estree/estree + + + +## Sponsors + +The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate) +to get your logo on our READMEs and [website](https://eslint.org/sponsors). + +

Diamond Sponsors

+

AG Grid

Platinum Sponsors

+

Automattic Airbnb

Gold Sponsors

+

Qlty Software trunk.io Shopify

Silver Sponsors

+

Vite Liftoff American Express StackBlitz

Bronze Sponsors

+

Sentry Syntax Cybozu Anagram Solver Icons8 Discord GitBook Neko Nx Mercedes-Benz Group HeroCoders LambdaTest

+

Technology Sponsors

+Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work. +

Netlify Algolia 1Password

+ diff --git a/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs b/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs new file mode 100644 index 0000000000000000000000000000000000000000..afc433c7cd5b094994f9eb79655873655544b368 --- /dev/null +++ b/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs @@ -0,0 +1,396 @@ +'use strict'; + +/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`. + TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed +*/ +/** + * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys + */ +/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly string[]`. TODO: check why */ + +/** + * @type {VisitorKeys} + */ +const KEYS = { + ArrayExpression: [ + "elements" + ], + ArrayPattern: [ + "elements" + ], + ArrowFunctionExpression: [ + "params", + "body" + ], + AssignmentExpression: [ + "left", + "right" + ], + AssignmentPattern: [ + "left", + "right" + ], + AwaitExpression: [ + "argument" + ], + BinaryExpression: [ + "left", + "right" + ], + BlockStatement: [ + "body" + ], + BreakStatement: [ + "label" + ], + CallExpression: [ + "callee", + "arguments" + ], + CatchClause: [ + "param", + "body" + ], + ChainExpression: [ + "expression" + ], + ClassBody: [ + "body" + ], + ClassDeclaration: [ + "id", + "superClass", + "body" + ], + ClassExpression: [ + "id", + "superClass", + "body" + ], + ConditionalExpression: [ + "test", + "consequent", + "alternate" + ], + ContinueStatement: [ + "label" + ], + DebuggerStatement: [], + DoWhileStatement: [ + "body", + "test" + ], + EmptyStatement: [], + ExperimentalRestProperty: [ + "argument" + ], + ExperimentalSpreadProperty: [ + "argument" + ], + ExportAllDeclaration: [ + "exported", + "source", + "attributes" + ], + ExportDefaultDeclaration: [ + "declaration" + ], + ExportNamedDeclaration: [ + "declaration", + "specifiers", + "source", + "attributes" + ], + ExportSpecifier: [ + "local", + "exported" + ], + ExpressionStatement: [ + "expression" + ], + ForInStatement: [ + "left", + "right", + "body" + ], + ForOfStatement: [ + "left", + "right", + "body" + ], + ForStatement: [ + "init", + "test", + "update", + "body" + ], + FunctionDeclaration: [ + "id", + "params", + "body" + ], + FunctionExpression: [ + "id", + "params", + "body" + ], + Identifier: [], + IfStatement: [ + "test", + "consequent", + "alternate" + ], + ImportAttribute: [ + "key", + "value" + ], + ImportDeclaration: [ + "specifiers", + "source", + "attributes" + ], + ImportDefaultSpecifier: [ + "local" + ], + ImportExpression: [ + "source", + "options" + ], + ImportNamespaceSpecifier: [ + "local" + ], + ImportSpecifier: [ + "imported", + "local" + ], + JSXAttribute: [ + "name", + "value" + ], + JSXClosingElement: [ + "name" + ], + JSXClosingFragment: [], + JSXElement: [ + "openingElement", + "children", + "closingElement" + ], + JSXEmptyExpression: [], + JSXExpressionContainer: [ + "expression" + ], + JSXFragment: [ + "openingFragment", + "children", + "closingFragment" + ], + JSXIdentifier: [], + JSXMemberExpression: [ + "object", + "property" + ], + JSXNamespacedName: [ + "namespace", + "name" + ], + JSXOpeningElement: [ + "name", + "attributes" + ], + JSXOpeningFragment: [], + JSXSpreadAttribute: [ + "argument" + ], + JSXSpreadChild: [ + "expression" + ], + JSXText: [], + LabeledStatement: [ + "label", + "body" + ], + Literal: [], + LogicalExpression: [ + "left", + "right" + ], + MemberExpression: [ + "object", + "property" + ], + MetaProperty: [ + "meta", + "property" + ], + MethodDefinition: [ + "key", + "value" + ], + NewExpression: [ + "callee", + "arguments" + ], + ObjectExpression: [ + "properties" + ], + ObjectPattern: [ + "properties" + ], + PrivateIdentifier: [], + Program: [ + "body" + ], + Property: [ + "key", + "value" + ], + PropertyDefinition: [ + "key", + "value" + ], + RestElement: [ + "argument" + ], + ReturnStatement: [ + "argument" + ], + SequenceExpression: [ + "expressions" + ], + SpreadElement: [ + "argument" + ], + StaticBlock: [ + "body" + ], + Super: [], + SwitchCase: [ + "test", + "consequent" + ], + SwitchStatement: [ + "discriminant", + "cases" + ], + TaggedTemplateExpression: [ + "tag", + "quasi" + ], + TemplateElement: [], + TemplateLiteral: [ + "quasis", + "expressions" + ], + ThisExpression: [], + ThrowStatement: [ + "argument" + ], + TryStatement: [ + "block", + "handler", + "finalizer" + ], + UnaryExpression: [ + "argument" + ], + UpdateExpression: [ + "argument" + ], + VariableDeclaration: [ + "declarations" + ], + VariableDeclarator: [ + "id", + "init" + ], + WhileStatement: [ + "test", + "body" + ], + WithStatement: [ + "object", + "body" + ], + YieldExpression: [ + "argument" + ] +}; + +// Types. +const NODE_TYPES = Object.keys(KEYS); + +// Freeze the keys. +for (const type of NODE_TYPES) { + Object.freeze(KEYS[type]); +} +Object.freeze(KEYS); + +/** + * @author Toru Nagashima + * See LICENSE file in root directory for full license. + */ + +/** + * @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys + */ + +// List to ignore keys. +const KEY_BLACKLIST = new Set([ + "parent", + "leadingComments", + "trailingComments" +]); + +/** + * Check whether a given key should be used or not. + * @param {string} key The key to check. + * @returns {boolean} `true` if the key should be used. + */ +function filterKey(key) { + return !KEY_BLACKLIST.has(key) && key[0] !== "_"; +} + + +/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`. + TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed +*/ +/** + * Get visitor keys of a given node. + * @param {Object} node The AST node to get keys. + * @returns {readonly string[]} Visitor keys of the node. + */ +function getKeys(node) { + return Object.keys(node).filter(filterKey); +} +/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly` */ + +/** + * Make the union set with `KEYS` and given keys. + * @param {VisitorKeys} additionalKeys The additional keys. + * @returns {VisitorKeys} The union set. + */ +function unionWith(additionalKeys) { + const retv = /** @type {{ [type: string]: ReadonlyArray }} */ + (Object.assign({}, KEYS)); + + for (const type of Object.keys(additionalKeys)) { + if (Object.hasOwn(retv, type)) { + const keys = new Set(additionalKeys[type]); + + for (const key of retv[type]) { + keys.add(key); + } + + retv[type] = Object.freeze(Array.from(keys)); + } else { + retv[type] = Object.freeze(Array.from(additionalKeys[type])); + } + } + + return Object.freeze(retv); +} + +exports.KEYS = KEYS; +exports.getKeys = getKeys; +exports.unionWith = unionWith; diff --git a/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts b/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..34253c96c3dd5035555c8ce96acd1b801f393935 --- /dev/null +++ b/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts @@ -0,0 +1,28 @@ +type VisitorKeys$1 = { + readonly [type: string]: ReadonlyArray; +}; +/** + * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys + */ +/** + * @type {VisitorKeys} + */ +declare const KEYS: VisitorKeys$1; + +/** + * Get visitor keys of a given node. + * @param {Object} node The AST node to get keys. + * @returns {readonly string[]} Visitor keys of the node. + */ +declare function getKeys(node: Object): readonly string[]; +/** + * Make the union set with `KEYS` and given keys. + * @param {VisitorKeys} additionalKeys The additional keys. + * @returns {VisitorKeys} The union set. + */ +declare function unionWith(additionalKeys: VisitorKeys): VisitorKeys; + +type VisitorKeys = VisitorKeys$1; + +export { KEYS, getKeys, unionWith }; +export type { VisitorKeys }; diff --git a/node_modules/eslint-visitor-keys/dist/index.d.ts b/node_modules/eslint-visitor-keys/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e65b7da338d3095bc7073a4f2e94c39b9c67223f --- /dev/null +++ b/node_modules/eslint-visitor-keys/dist/index.d.ts @@ -0,0 +1,16 @@ +/** + * Get visitor keys of a given node. + * @param {Object} node The AST node to get keys. + * @returns {readonly string[]} Visitor keys of the node. + */ +export function getKeys(node: Object): readonly string[]; +/** + * Make the union set with `KEYS` and given keys. + * @param {VisitorKeys} additionalKeys The additional keys. + * @returns {VisitorKeys} The union set. + */ +export function unionWith(additionalKeys: VisitorKeys): VisitorKeys; +export { KEYS }; +export type VisitorKeys = import("./visitor-keys.js").VisitorKeys; +import KEYS from "./visitor-keys.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts b/node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2d7ada2f1d5d0cdd0253e1f0e04be4407f91f20f --- /dev/null +++ b/node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts @@ -0,0 +1,12 @@ +export default KEYS; +export type VisitorKeys = { + readonly [type: string]: ReadonlyArray; +}; +/** + * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys + */ +/** + * @type {VisitorKeys} + */ +declare const KEYS: VisitorKeys; +//# sourceMappingURL=visitor-keys.d.ts.map \ No newline at end of file diff --git a/node_modules/eslint-visitor-keys/lib/index.js b/node_modules/eslint-visitor-keys/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1fc89b43dcb906c169e543d0cb6e3257aa86788a --- /dev/null +++ b/node_modules/eslint-visitor-keys/lib/index.js @@ -0,0 +1,67 @@ +/** + * @author Toru Nagashima + * See LICENSE file in root directory for full license. + */ +import KEYS from "./visitor-keys.js"; + +/** + * @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys + */ + +// List to ignore keys. +const KEY_BLACKLIST = new Set([ + "parent", + "leadingComments", + "trailingComments" +]); + +/** + * Check whether a given key should be used or not. + * @param {string} key The key to check. + * @returns {boolean} `true` if the key should be used. + */ +function filterKey(key) { + return !KEY_BLACKLIST.has(key) && key[0] !== "_"; +} + + +/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`. + TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed +*/ +/** + * Get visitor keys of a given node. + * @param {Object} node The AST node to get keys. + * @returns {readonly string[]} Visitor keys of the node. + */ +export function getKeys(node) { + return Object.keys(node).filter(filterKey); +} +/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly` */ + +/** + * Make the union set with `KEYS` and given keys. + * @param {VisitorKeys} additionalKeys The additional keys. + * @returns {VisitorKeys} The union set. + */ +export function unionWith(additionalKeys) { + const retv = /** @type {{ [type: string]: ReadonlyArray }} */ + (Object.assign({}, KEYS)); + + for (const type of Object.keys(additionalKeys)) { + if (Object.hasOwn(retv, type)) { + const keys = new Set(additionalKeys[type]); + + for (const key of retv[type]) { + keys.add(key); + } + + retv[type] = Object.freeze(Array.from(keys)); + } else { + retv[type] = Object.freeze(Array.from(additionalKeys[type])); + } + } + + return Object.freeze(retv); +} + +export { KEYS }; diff --git a/node_modules/eslint-visitor-keys/lib/visitor-keys.js b/node_modules/eslint-visitor-keys/lib/visitor-keys.js new file mode 100644 index 0000000000000000000000000000000000000000..c891e040af322399afd225ca4f091fcbbecc7a96 --- /dev/null +++ b/node_modules/eslint-visitor-keys/lib/visitor-keys.js @@ -0,0 +1,327 @@ +/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`. + TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed +*/ +/** + * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys + */ +/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly string[]`. TODO: check why */ + +/** + * @type {VisitorKeys} + */ +const KEYS = { + ArrayExpression: [ + "elements" + ], + ArrayPattern: [ + "elements" + ], + ArrowFunctionExpression: [ + "params", + "body" + ], + AssignmentExpression: [ + "left", + "right" + ], + AssignmentPattern: [ + "left", + "right" + ], + AwaitExpression: [ + "argument" + ], + BinaryExpression: [ + "left", + "right" + ], + BlockStatement: [ + "body" + ], + BreakStatement: [ + "label" + ], + CallExpression: [ + "callee", + "arguments" + ], + CatchClause: [ + "param", + "body" + ], + ChainExpression: [ + "expression" + ], + ClassBody: [ + "body" + ], + ClassDeclaration: [ + "id", + "superClass", + "body" + ], + ClassExpression: [ + "id", + "superClass", + "body" + ], + ConditionalExpression: [ + "test", + "consequent", + "alternate" + ], + ContinueStatement: [ + "label" + ], + DebuggerStatement: [], + DoWhileStatement: [ + "body", + "test" + ], + EmptyStatement: [], + ExperimentalRestProperty: [ + "argument" + ], + ExperimentalSpreadProperty: [ + "argument" + ], + ExportAllDeclaration: [ + "exported", + "source", + "attributes" + ], + ExportDefaultDeclaration: [ + "declaration" + ], + ExportNamedDeclaration: [ + "declaration", + "specifiers", + "source", + "attributes" + ], + ExportSpecifier: [ + "local", + "exported" + ], + ExpressionStatement: [ + "expression" + ], + ForInStatement: [ + "left", + "right", + "body" + ], + ForOfStatement: [ + "left", + "right", + "body" + ], + ForStatement: [ + "init", + "test", + "update", + "body" + ], + FunctionDeclaration: [ + "id", + "params", + "body" + ], + FunctionExpression: [ + "id", + "params", + "body" + ], + Identifier: [], + IfStatement: [ + "test", + "consequent", + "alternate" + ], + ImportAttribute: [ + "key", + "value" + ], + ImportDeclaration: [ + "specifiers", + "source", + "attributes" + ], + ImportDefaultSpecifier: [ + "local" + ], + ImportExpression: [ + "source", + "options" + ], + ImportNamespaceSpecifier: [ + "local" + ], + ImportSpecifier: [ + "imported", + "local" + ], + JSXAttribute: [ + "name", + "value" + ], + JSXClosingElement: [ + "name" + ], + JSXClosingFragment: [], + JSXElement: [ + "openingElement", + "children", + "closingElement" + ], + JSXEmptyExpression: [], + JSXExpressionContainer: [ + "expression" + ], + JSXFragment: [ + "openingFragment", + "children", + "closingFragment" + ], + JSXIdentifier: [], + JSXMemberExpression: [ + "object", + "property" + ], + JSXNamespacedName: [ + "namespace", + "name" + ], + JSXOpeningElement: [ + "name", + "attributes" + ], + JSXOpeningFragment: [], + JSXSpreadAttribute: [ + "argument" + ], + JSXSpreadChild: [ + "expression" + ], + JSXText: [], + LabeledStatement: [ + "label", + "body" + ], + Literal: [], + LogicalExpression: [ + "left", + "right" + ], + MemberExpression: [ + "object", + "property" + ], + MetaProperty: [ + "meta", + "property" + ], + MethodDefinition: [ + "key", + "value" + ], + NewExpression: [ + "callee", + "arguments" + ], + ObjectExpression: [ + "properties" + ], + ObjectPattern: [ + "properties" + ], + PrivateIdentifier: [], + Program: [ + "body" + ], + Property: [ + "key", + "value" + ], + PropertyDefinition: [ + "key", + "value" + ], + RestElement: [ + "argument" + ], + ReturnStatement: [ + "argument" + ], + SequenceExpression: [ + "expressions" + ], + SpreadElement: [ + "argument" + ], + StaticBlock: [ + "body" + ], + Super: [], + SwitchCase: [ + "test", + "consequent" + ], + SwitchStatement: [ + "discriminant", + "cases" + ], + TaggedTemplateExpression: [ + "tag", + "quasi" + ], + TemplateElement: [], + TemplateLiteral: [ + "quasis", + "expressions" + ], + ThisExpression: [], + ThrowStatement: [ + "argument" + ], + TryStatement: [ + "block", + "handler", + "finalizer" + ], + UnaryExpression: [ + "argument" + ], + UpdateExpression: [ + "argument" + ], + VariableDeclaration: [ + "declarations" + ], + VariableDeclarator: [ + "id", + "init" + ], + WhileStatement: [ + "test", + "body" + ], + WithStatement: [ + "object", + "body" + ], + YieldExpression: [ + "argument" + ] +}; + +// Types. +const NODE_TYPES = Object.keys(KEYS); + +// Freeze the keys. +for (const type of NODE_TYPES) { + Object.freeze(KEYS[type]); +} +Object.freeze(KEYS); + +export default KEYS; diff --git a/node_modules/eslint-visitor-keys/package.json b/node_modules/eslint-visitor-keys/package.json new file mode 100644 index 0000000000000000000000000000000000000000..852e4ddb18cc908e63f0de3006190d30d1f3d213 --- /dev/null +++ b/node_modules/eslint-visitor-keys/package.json @@ -0,0 +1,70 @@ +{ + "name": "eslint-visitor-keys", + "version": "4.2.1", + "description": "Constants and utilities about visitor keys to traverse AST.", + "type": "module", + "main": "dist/eslint-visitor-keys.cjs", + "types": "./dist/index.d.ts", + "exports": { + ".": [ + { + "import": "./lib/index.js", + "require": "./dist/eslint-visitor-keys.cjs" + }, + "./dist/eslint-visitor-keys.cjs" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist/index.d.ts", + "dist/visitor-keys.d.ts", + "dist/eslint-visitor-keys.cjs", + "dist/eslint-visitor-keys.d.cts", + "lib" + ], + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "devDependencies": { + "@types/estree": "^0.0.51", + "@types/estree-jsx": "^0.0.1", + "@typescript-eslint/parser": "^8.7.0", + "eslint-release": "^3.2.0", + "esquery": "^1.4.0", + "json-diff": "^0.7.3", + "opener": "^1.5.2", + "rollup": "^4.22.4", + "rollup-plugin-dts": "^6.1.1", + "tsd": "^0.31.2", + "typescript": "^5.6.2" + }, + "scripts": { + "build": "npm run build:cjs && npm run build:types", + "build:cjs": "rollup -c", + "build:debug": "npm run build:cjs -- -m && npm run build:types", + "build:types": "tsc -v && tsc", + "release:generate:latest": "eslint-generate-release", + "release:generate:alpha": "eslint-generate-prerelease alpha", + "release:generate:beta": "eslint-generate-prerelease beta", + "release:generate:rc": "eslint-generate-prerelease rc", + "release:publish": "eslint-publish-release", + "test": "mocha tests/lib/**/*.cjs && c8 mocha tests/lib/**/*.js && npm run test:types", + "test:open-coverage": "c8 report --reporter lcov && opener coverage/lcov-report/index.html", + "test:types": "tsd" + }, + "repository": { + "type": "git", + "url": "https://github.com/eslint/js.git", + "directory": "packages/eslint-visitor-keys" + }, + "funding": "https://opencollective.com/eslint", + "keywords": [ + "eslint" + ], + "author": "Toru Nagashima (https://github.com/mysticatea)", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/eslint/js/issues" + }, + "homepage": "https://github.com/eslint/js/blob/main/packages/eslint-visitor-keys/README.md" +} diff --git a/node_modules/espree/LICENSE b/node_modules/espree/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b18469ff2ffdfcf437456350a4bee3ba493f1970 --- /dev/null +++ b/node_modules/espree/LICENSE @@ -0,0 +1,25 @@ +BSD 2-Clause License + +Copyright (c) Open JS Foundation +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +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 HOLDER 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. diff --git a/node_modules/espree/README.md b/node_modules/espree/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e8e73ee5f26dcaa257e84d6ffed1d073f1195387 --- /dev/null +++ b/node_modules/espree/README.md @@ -0,0 +1,262 @@ +[![npm version](https://img.shields.io/npm/v/espree.svg)](https://www.npmjs.com/package/espree) +[![npm downloads](https://img.shields.io/npm/dm/espree.svg)](https://www.npmjs.com/package/espree) +[![Build Status](https://github.com/eslint/js/workflows/CI/badge.svg)](https://github.com/js/espree/actions) +[![Bountysource](https://www.bountysource.com/badge/tracker?tracker_id=9348450)](https://www.bountysource.com/trackers/9348450-eslint?utm_source=9348450&utm_medium=shield&utm_campaign=TRACKER_BADGE) + +# Espree + +Espree started out as a fork of [Esprima](http://esprima.org) v1.2.2, the last stable published released of Esprima before work on ECMAScript 6 began. Espree is now built on top of [Acorn](https://github.com/ternjs/acorn), which has a modular architecture that allows extension of core functionality. The goal of Espree is to produce output that is similar to Esprima with a similar API so that it can be used in place of Esprima. + +## Usage + +Install: + +``` +npm i espree +``` + +To use in an ESM file: + +```js +import * as espree from "espree"; + +const ast = espree.parse(code); +``` + +To use in a Common JS file: + +```js +const espree = require("espree"); + +const ast = espree.parse(code); +``` + +## API + +### `parse()` + +`parse` parses the given code and returns a abstract syntax tree (AST). It takes two parameters. + +- `code` [string]() - the code which needs to be parsed. +- `options (Optional)` [Object]() - read more about this [here](#options). + +```js +import * as espree from "espree"; + +const ast = espree.parse(code); +``` + +**Example :** + +```js +const ast = espree.parse('let foo = "bar"', { ecmaVersion: 6 }); +console.log(ast); +``` + +
Output +

+ +``` +Node { + type: 'Program', + start: 0, + end: 15, + body: [ + Node { + type: 'VariableDeclaration', + start: 0, + end: 15, + declarations: [Array], + kind: 'let' + } + ], + sourceType: 'script' +} +``` + +

+
+ +### `tokenize()` + +`tokenize` returns the tokens of a given code. It takes two parameters. + +- `code` [string]() - the code which needs to be parsed. +- `options (Optional)` [Object]() - read more about this [here](#options). + +Even if `options` is empty or undefined or `options.tokens` is `false`, it assigns it to `true` in order to get the `tokens` array + +**Example :** + +```js +import * as espree from "espree"; + +const tokens = espree.tokenize('let foo = "bar"', { ecmaVersion: 6 }); +console.log(tokens); +``` + +
Output +

+ +``` +Token { type: 'Keyword', value: 'let', start: 0, end: 3 }, +Token { type: 'Identifier', value: 'foo', start: 4, end: 7 }, +Token { type: 'Punctuator', value: '=', start: 8, end: 9 }, +Token { type: 'String', value: '"bar"', start: 10, end: 15 } +``` + +

+
+ +### `version` + +Returns the current `espree` version + +### `VisitorKeys` + +Returns all visitor keys for traversing the AST from [eslint-visitor-keys](https://github.com/eslint/js/tree/main/packages/eslint-visitor-keys) + +### `latestEcmaVersion` + +Returns the latest ECMAScript supported by `espree` + +### `supportedEcmaVersions` + +Returns an array of all supported ECMAScript versions + +## Options + +```js +const options = { + // attach range information to each node + range: false, + + // attach line/column location information to each node + loc: false, + + // create a top-level comments array containing all comments + comment: false, + + // create a top-level tokens array containing all tokens + tokens: false, + + // Set to 3, 5 (the default), 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 or 17 to specify the version of ECMAScript syntax you want to use. + // You can also set to 2015 (same as 6), 2016 (same as 7), 2017 (same as 8), 2018 (same as 9), 2019 (same as 10), 2020 (same as 11), 2021 (same as 12), 2022 (same as 13), 2023 (same as 14), 2024 (same as 15), 2025 (same as 16) or 2026 (same as 17) to use the year-based naming. + // You can also set "latest" to use the most recently supported version. + ecmaVersion: 3, + + allowReserved: true, // only allowed when ecmaVersion is 3 + + // specify which type of script you're parsing ("script", "module", or "commonjs") + sourceType: "script", + + // specify additional language features + ecmaFeatures: { + + // enable JSX parsing + jsx: false, + + // enable return in global scope (set to true automatically when sourceType is "commonjs") + globalReturn: false, + + // enable implied strict mode (if ecmaVersion >= 5) + impliedStrict: false + } +} +``` + +## Esprima Compatibility Going Forward + +The primary goal is to produce the exact same AST structure and tokens as Esprima, and that takes precedence over anything else. (The AST structure being the [ESTree](https://github.com/estree/estree) API with JSX extensions.) Separate from that, Espree may deviate from what Esprima outputs in terms of where and how comments are attached, as well as what additional information is available on AST nodes. That is to say, Espree may add more things to the AST nodes than Esprima does but the overall AST structure produced will be the same. + +Espree may also deviate from Esprima in the interface it exposes. + +## Contributing + +Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/js/issues). + +Espree is licensed under a permissive BSD 2-clause license. + +## Security Policy + +We work hard to ensure that Espree is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md). + +## Build Commands + +* `npm test` - run all tests +* `npm run lint` - run all linting + +## Differences from Espree 2.x + +* The `tokenize()` method does not use `ecmaFeatures`. Any string will be tokenized completely based on ECMAScript 6 semantics. +* Trailing whitespace no longer is counted as part of a node. +* `let` and `const` declarations are no longer parsed by default. You must opt-in by using an `ecmaVersion` newer than `5` or setting `sourceType` to `module`. +* The `esparse` and `esvalidate` binary scripts have been removed. +* There is no `tolerant` option. We will investigate adding this back in the future. + +## Known Incompatibilities + +In an effort to help those wanting to transition from other parsers to Espree, the following is a list of noteworthy incompatibilities with other parsers. These are known differences that we do not intend to change. + +### Esprima 1.2.2 + +* Esprima counts trailing whitespace as part of each AST node while Espree does not. In Espree, the end of a node is where the last token occurs. +* Espree does not parse `let` and `const` declarations by default. +* Error messages returned for parsing errors are different. +* There are two addition properties on every node and token: `start` and `end`. These represent the same data as `range` and are used internally by Acorn. + +### Esprima 2.x + +* Esprima 2.x uses a different comment attachment algorithm that results in some comments being added in different places than Espree. The algorithm Espree uses is the same one used in Esprima 1.2.2. + +## Frequently Asked Questions + +### Why another parser + +[ESLint](http://eslint.org) had been relying on Esprima as its parser from the beginning. While that was fine when the JavaScript language was evolving slowly, the pace of development increased dramatically and Esprima had fallen behind. ESLint, like many other tools reliant on Esprima, has been stuck in using new JavaScript language features until Esprima updates, and that caused our users frustration. + +We decided the only way for us to move forward was to create our own parser, bringing us inline with JSHint and JSLint, and allowing us to keep implementing new features as we need them. We chose to fork Esprima instead of starting from scratch in order to move as quickly as possible with a compatible API. + +With Espree 2.0.0, we are no longer a fork of Esprima but rather a translation layer between Acorn and Esprima syntax. This allows us to put work back into a community-supported parser (Acorn) that is continuing to grow and evolve while maintaining an Esprima-compatible parser for those utilities still built on Esprima. + +### Have you tried working with Esprima? + +Yes. Since the start of ESLint, we've regularly filed bugs and feature requests with Esprima and will continue to do so. However, there are some different philosophies around how the projects work that need to be worked through. The initial goal was to have Espree track Esprima and eventually merge the two back together, but we ultimately decided that building on top of Acorn was a better choice due to Acorn's plugin support. + +### Why don't you just use Acorn? + +Acorn is a great JavaScript parser that produces an AST that is compatible with Esprima. Unfortunately, ESLint relies on more than just the AST to do its job. It relies on Esprima's tokens and comment attachment features to get a complete picture of the source code. We investigated switching to Acorn, but the inconsistencies between Esprima and Acorn created too much work for a project like ESLint. + +We are building on top of Acorn, however, so that we can contribute back and help make Acorn even better. + +### What ECMAScript features do you support? + +Espree supports all ECMAScript 2025 features and partially supports ECMAScript 2026 features. + +Because ECMAScript 2026 is still under development, we are implementing features as they are finalized. Currently, Espree supports: + +* [Explicit Resource Management](https://github.com/tc39/proposal-explicit-resource-management) + +See [finished-proposals.md](https://github.com/tc39/proposals/blob/master/finished-proposals.md) to know what features are finalized. + +### How do you determine which experimental features to support? + +In general, we do not support experimental JavaScript features. We may make exceptions from time to time depending on the maturity of the features. + + + +## Sponsors + +The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate) +to get your logo on our READMEs and [website](https://eslint.org/sponsors). + +

Diamond Sponsors

+

AG Grid

Platinum Sponsors

+

Automattic Airbnb

Gold Sponsors

+

Qlty Software trunk.io Shopify

Silver Sponsors

+

Vite Liftoff American Express StackBlitz

Bronze Sponsors

+

Sentry Syntax Cybozu Anagram Solver Icons8 Discord GitBook Neko Nx Mercedes-Benz Group HeroCoders LambdaTest

+

Technology Sponsors

+Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work. +

Netlify Algolia 1Password

+ diff --git a/node_modules/espree/dist/espree.cjs b/node_modules/espree/dist/espree.cjs new file mode 100644 index 0000000000000000000000000000000000000000..0abd6b27b5b29319c4d13f214546d7cd439ef624 --- /dev/null +++ b/node_modules/espree/dist/espree.cjs @@ -0,0 +1,940 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var acorn = require('acorn'); +var jsx = require('acorn-jsx'); +var visitorKeys = require('eslint-visitor-keys'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); +} + +var acorn__namespace = /*#__PURE__*/_interopNamespace(acorn); +var jsx__default = /*#__PURE__*/_interopDefaultLegacy(jsx); +var visitorKeys__namespace = /*#__PURE__*/_interopNamespace(visitorKeys); + +/** + * @fileoverview Translates tokens between Acorn format and Esprima format. + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +// none! + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + + +// Esprima Token Types +const Token = { + Boolean: "Boolean", + EOF: "", + Identifier: "Identifier", + PrivateIdentifier: "PrivateIdentifier", + Keyword: "Keyword", + Null: "Null", + Numeric: "Numeric", + Punctuator: "Punctuator", + String: "String", + RegularExpression: "RegularExpression", + Template: "Template", + JSXIdentifier: "JSXIdentifier", + JSXText: "JSXText" +}; + +/** + * Converts part of a template into an Esprima token. + * @param {AcornToken[]} tokens The Acorn tokens representing the template. + * @param {string} code The source code. + * @returns {EsprimaToken} The Esprima equivalent of the template token. + * @private + */ +function convertTemplatePart(tokens, code) { + const firstToken = tokens[0], + lastTemplateToken = tokens.at(-1); + + const token = { + type: Token.Template, + value: code.slice(firstToken.start, lastTemplateToken.end) + }; + + if (firstToken.loc) { + token.loc = { + start: firstToken.loc.start, + end: lastTemplateToken.loc.end + }; + } + + if (firstToken.range) { + token.start = firstToken.range[0]; + token.end = lastTemplateToken.range[1]; + token.range = [token.start, token.end]; + } + + return token; +} + +/** + * Contains logic to translate Acorn tokens into Esprima tokens. + * @param {Object} acornTokTypes The Acorn token types. + * @param {string} code The source code Acorn is parsing. This is necessary + * to correct the "value" property of some tokens. + * @constructor + */ +function TokenTranslator(acornTokTypes, code) { + + // token types + this._acornTokTypes = acornTokTypes; + + // token buffer for templates + this._tokens = []; + + // track the last curly brace + this._curlyBrace = null; + + // the source code + this._code = code; + +} + +TokenTranslator.prototype = { + constructor: TokenTranslator, + + /** + * Translates a single Esprima token to a single Acorn token. This may be + * inaccurate due to how templates are handled differently in Esprima and + * Acorn, but should be accurate for all other tokens. + * @param {AcornToken} token The Acorn token to translate. + * @param {Object} extra Espree extra object. + * @returns {EsprimaToken} The Esprima version of the token. + */ + translate(token, extra) { + + const type = token.type, + tt = this._acornTokTypes; + + if (type === tt.name) { + token.type = Token.Identifier; + + // TODO: See if this is an Acorn bug + if (token.value === "static") { + token.type = Token.Keyword; + } + + if (extra.ecmaVersion > 5 && (token.value === "yield" || token.value === "let")) { + token.type = Token.Keyword; + } + + } else if (type === tt.privateId) { + token.type = Token.PrivateIdentifier; + + } else if (type === tt.semi || type === tt.comma || + type === tt.parenL || type === tt.parenR || + type === tt.braceL || type === tt.braceR || + type === tt.dot || type === tt.bracketL || + type === tt.colon || type === tt.question || + type === tt.bracketR || type === tt.ellipsis || + type === tt.arrow || type === tt.jsxTagStart || + type === tt.incDec || type === tt.starstar || + type === tt.jsxTagEnd || type === tt.prefix || + type === tt.questionDot || + (type.binop && !type.keyword) || + type.isAssign) { + + token.type = Token.Punctuator; + token.value = this._code.slice(token.start, token.end); + } else if (type === tt.jsxName) { + token.type = Token.JSXIdentifier; + } else if (type.label === "jsxText" || type === tt.jsxAttrValueToken) { + token.type = Token.JSXText; + } else if (type.keyword) { + if (type.keyword === "true" || type.keyword === "false") { + token.type = Token.Boolean; + } else if (type.keyword === "null") { + token.type = Token.Null; + } else { + token.type = Token.Keyword; + } + } else if (type === tt.num) { + token.type = Token.Numeric; + token.value = this._code.slice(token.start, token.end); + } else if (type === tt.string) { + + if (extra.jsxAttrValueToken) { + extra.jsxAttrValueToken = false; + token.type = Token.JSXText; + } else { + token.type = Token.String; + } + + token.value = this._code.slice(token.start, token.end); + } else if (type === tt.regexp) { + token.type = Token.RegularExpression; + const value = token.value; + + token.regex = { + flags: value.flags, + pattern: value.pattern + }; + token.value = `/${value.pattern}/${value.flags}`; + } + + return token; + }, + + /** + * Function to call during Acorn's onToken handler. + * @param {AcornToken} token The Acorn token. + * @param {Object} extra The Espree extra object. + * @returns {void} + */ + onToken(token, extra) { + + const tt = this._acornTokTypes, + tokens = extra.tokens, + templateTokens = this._tokens; + + /** + * Flushes the buffered template tokens and resets the template + * tracking. + * @returns {void} + * @private + */ + const translateTemplateTokens = () => { + tokens.push(convertTemplatePart(this._tokens, this._code)); + this._tokens = []; + }; + + if (token.type === tt.eof) { + + // might be one last curlyBrace + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + } + + return; + } + + if (token.type === tt.backQuote) { + + // if there's already a curly, it's not part of the template + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + this._curlyBrace = null; + } + + templateTokens.push(token); + + // it's the end + if (templateTokens.length > 1) { + translateTemplateTokens(); + } + + return; + } + if (token.type === tt.dollarBraceL) { + templateTokens.push(token); + translateTemplateTokens(); + return; + } + if (token.type === tt.braceR) { + + // if there's already a curly, it's not part of the template + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + } + + // store new curly for later + this._curlyBrace = token; + return; + } + if (token.type === tt.template || token.type === tt.invalidTemplate) { + if (this._curlyBrace) { + templateTokens.push(this._curlyBrace); + this._curlyBrace = null; + } + + templateTokens.push(token); + return; + } + + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + this._curlyBrace = null; + } + + tokens.push(this.translate(token, extra)); + } +}; + +/** + * @fileoverview A collection of methods for processing Espree's options. + * @author Kai Cataldo + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SUPPORTED_VERSIONS = [ + 3, + 5, + 6, // 2015 + 7, // 2016 + 8, // 2017 + 9, // 2018 + 10, // 2019 + 11, // 2020 + 12, // 2021 + 13, // 2022 + 14, // 2023 + 15, // 2024 + 16, // 2025 + 17 // 2026 +]; + +/** + * Get the latest ECMAScript version supported by Espree. + * @returns {number} The latest ECMAScript version. + */ +function getLatestEcmaVersion() { + return SUPPORTED_VERSIONS.at(-1); +} + +/** + * Get the list of ECMAScript versions supported by Espree. + * @returns {number[]} An array containing the supported ECMAScript versions. + */ +function getSupportedEcmaVersions() { + return [...SUPPORTED_VERSIONS]; +} + +/** + * Normalize ECMAScript version from the initial config + * @param {(number|"latest")} ecmaVersion ECMAScript version from the initial config + * @throws {Error} throws an error if the ecmaVersion is invalid. + * @returns {number} normalized ECMAScript version + */ +function normalizeEcmaVersion(ecmaVersion = 5) { + + let version = ecmaVersion === "latest" ? getLatestEcmaVersion() : ecmaVersion; + + if (typeof version !== "number") { + throw new Error(`ecmaVersion must be a number or "latest". Received value of type ${typeof ecmaVersion} instead.`); + } + + // Calculate ECMAScript edition number from official year version starting with + // ES2015, which corresponds with ES6 (or a difference of 2009). + if (version >= 2015) { + version -= 2009; + } + + if (!SUPPORTED_VERSIONS.includes(version)) { + throw new Error("Invalid ecmaVersion."); + } + + return version; +} + +/** + * Normalize sourceType from the initial config + * @param {string} sourceType to normalize + * @throws {Error} throw an error if sourceType is invalid + * @returns {string} normalized sourceType + */ +function normalizeSourceType(sourceType = "script") { + if (sourceType === "script" || sourceType === "module") { + return sourceType; + } + + if (sourceType === "commonjs") { + return "script"; + } + + throw new Error("Invalid sourceType."); +} + +/** + * Normalize parserOptions + * @param {Object} options the parser options to normalize + * @throws {Error} throw an error if found invalid option. + * @returns {Object} normalized options + */ +function normalizeOptions(options) { + const ecmaVersion = normalizeEcmaVersion(options.ecmaVersion); + const sourceType = normalizeSourceType(options.sourceType); + const ranges = options.range === true; + const locations = options.loc === true; + + if (ecmaVersion !== 3 && options.allowReserved) { + + // a value of `false` is intentionally allowed here, so a shared config can overwrite it when needed + throw new Error("`allowReserved` is only supported when ecmaVersion is 3"); + } + if (typeof options.allowReserved !== "undefined" && typeof options.allowReserved !== "boolean") { + throw new Error("`allowReserved`, when present, must be `true` or `false`"); + } + const allowReserved = ecmaVersion === 3 ? (options.allowReserved || "never") : false; + const ecmaFeatures = options.ecmaFeatures || {}; + const allowReturnOutsideFunction = options.sourceType === "commonjs" || + Boolean(ecmaFeatures.globalReturn); + + if (sourceType === "module" && ecmaVersion < 6) { + throw new Error("sourceType 'module' is not supported when ecmaVersion < 2015. Consider adding `{ ecmaVersion: 2015 }` to the parser options."); + } + + return Object.assign({}, options, { + ecmaVersion, + sourceType, + ranges, + locations, + allowReserved, + allowReturnOutsideFunction + }); +} + +/* eslint no-param-reassign: 0 -- stylistic choice */ + + +const STATE = Symbol("espree's internal state"); +const ESPRIMA_FINISH_NODE = Symbol("espree's esprimaFinishNode"); + + +/** + * Converts an Acorn comment to a Esprima comment. + * @param {boolean} block True if it's a block comment, false if not. + * @param {string} text The text of the comment. + * @param {int} start The index at which the comment starts. + * @param {int} end The index at which the comment ends. + * @param {Location} startLoc The location at which the comment starts. + * @param {Location} endLoc The location at which the comment ends. + * @param {string} code The source code being parsed. + * @returns {Object} The comment object. + * @private + */ +function convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc, code) { + let type; + + if (block) { + type = "Block"; + } else if (code.slice(start, start + 2) === "#!") { + type = "Hashbang"; + } else { + type = "Line"; + } + + const comment = { + type, + value: text + }; + + if (typeof start === "number") { + comment.start = start; + comment.end = end; + comment.range = [start, end]; + } + + if (typeof startLoc === "object") { + comment.loc = { + start: startLoc, + end: endLoc + }; + } + + return comment; +} + +var espree = () => Parser => { + const tokTypes = Object.assign({}, Parser.acorn.tokTypes); + + if (Parser.acornJsx) { + Object.assign(tokTypes, Parser.acornJsx.tokTypes); + } + + return class Espree extends Parser { + constructor(opts, code) { + if (typeof opts !== "object" || opts === null) { + opts = {}; + } + if (typeof code !== "string" && !(code instanceof String)) { + code = String(code); + } + + // save original source type in case of commonjs + const originalSourceType = opts.sourceType; + const options = normalizeOptions(opts); + const ecmaFeatures = options.ecmaFeatures || {}; + const tokenTranslator = + options.tokens === true + ? new TokenTranslator(tokTypes, code) + : null; + + /* + * Data that is unique to Espree and is not represented internally + * in Acorn. + * + * For ES2023 hashbangs, Espree will call `onComment()` during the + * constructor, so we must define state before having access to + * `this`. + */ + const state = { + originalSourceType: originalSourceType || options.sourceType, + tokens: tokenTranslator ? [] : null, + comments: options.comment === true ? [] : null, + impliedStrict: ecmaFeatures.impliedStrict === true && options.ecmaVersion >= 5, + ecmaVersion: options.ecmaVersion, + jsxAttrValueToken: false, + lastToken: null, + templateElements: [] + }; + + // Initialize acorn parser. + super({ + + // do not use spread, because we don't want to pass any unknown options to acorn + ecmaVersion: options.ecmaVersion, + sourceType: options.sourceType, + ranges: options.ranges, + locations: options.locations, + allowReserved: options.allowReserved, + + // Truthy value is true for backward compatibility. + allowReturnOutsideFunction: options.allowReturnOutsideFunction, + + // Collect tokens + onToken(token) { + if (tokenTranslator) { + + // Use `tokens`, `ecmaVersion`, and `jsxAttrValueToken` in the state. + tokenTranslator.onToken(token, state); + } + if (token.type !== tokTypes.eof) { + state.lastToken = token; + } + }, + + // Collect comments + onComment(block, text, start, end, startLoc, endLoc) { + if (state.comments) { + const comment = convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc, code); + + state.comments.push(comment); + } + } + }, code); + + /* + * We put all of this data into a symbol property as a way to avoid + * potential naming conflicts with future versions of Acorn. + */ + this[STATE] = state; + } + + tokenize() { + do { + this.next(); + } while (this.type !== tokTypes.eof); + + // Consume the final eof token + this.next(); + + const extra = this[STATE]; + const tokens = extra.tokens; + + if (extra.comments) { + tokens.comments = extra.comments; + } + + return tokens; + } + + finishNode(...args) { + const result = super.finishNode(...args); + + return this[ESPRIMA_FINISH_NODE](result); + } + + finishNodeAt(...args) { + const result = super.finishNodeAt(...args); + + return this[ESPRIMA_FINISH_NODE](result); + } + + parse() { + const extra = this[STATE]; + const program = super.parse(); + + program.sourceType = extra.originalSourceType; + + if (extra.comments) { + program.comments = extra.comments; + } + if (extra.tokens) { + program.tokens = extra.tokens; + } + + /* + * Adjust opening and closing position of program to match Esprima. + * Acorn always starts programs at range 0 whereas Esprima starts at the + * first AST node's start (the only real difference is when there's leading + * whitespace or leading comments). Acorn also counts trailing whitespace + * as part of the program whereas Esprima only counts up to the last token. + */ + if (program.body.length) { + const [firstNode] = program.body; + + if (program.range) { + program.range[0] = firstNode.range[0]; + } + if (program.loc) { + program.loc.start = firstNode.loc.start; + } + program.start = firstNode.start; + } + if (extra.lastToken) { + if (program.range) { + program.range[1] = extra.lastToken.range[1]; + } + if (program.loc) { + program.loc.end = extra.lastToken.loc.end; + } + program.end = extra.lastToken.end; + } + + + /* + * https://github.com/eslint/espree/issues/349 + * Ensure that template elements have correct range information. + * This is one location where Acorn produces a different value + * for its start and end properties vs. the values present in the + * range property. In order to avoid confusion, we set the start + * and end properties to the values that are present in range. + * This is done here, instead of in finishNode(), because Acorn + * uses the values of start and end internally while parsing, making + * it dangerous to change those values while parsing is ongoing. + * By waiting until the end of parsing, we can safely change these + * values without affect any other part of the process. + */ + this[STATE].templateElements.forEach(templateElement => { + const startOffset = -1; + const endOffset = templateElement.tail ? 1 : 2; + + templateElement.start += startOffset; + templateElement.end += endOffset; + + if (templateElement.range) { + templateElement.range[0] += startOffset; + templateElement.range[1] += endOffset; + } + + if (templateElement.loc) { + templateElement.loc.start.column += startOffset; + templateElement.loc.end.column += endOffset; + } + }); + + return program; + } + + parseTopLevel(node) { + if (this[STATE].impliedStrict) { + this.strict = true; + } + return super.parseTopLevel(node); + } + + /** + * Overwrites the default raise method to throw Esprima-style errors. + * @param {int} pos The position of the error. + * @param {string} message The error message. + * @throws {SyntaxError} A syntax error. + * @returns {void} + */ + raise(pos, message) { + const loc = Parser.acorn.getLineInfo(this.input, pos); + const err = new SyntaxError(message); + + err.index = pos; + err.lineNumber = loc.line; + err.column = loc.column + 1; // acorn uses 0-based columns + throw err; + } + + /** + * Overwrites the default raise method to throw Esprima-style errors. + * @param {int} pos The position of the error. + * @param {string} message The error message. + * @throws {SyntaxError} A syntax error. + * @returns {void} + */ + raiseRecoverable(pos, message) { + this.raise(pos, message); + } + + /** + * Overwrites the default unexpected method to throw Esprima-style errors. + * @param {int} pos The position of the error. + * @throws {SyntaxError} A syntax error. + * @returns {void} + */ + unexpected(pos) { + let message = "Unexpected token"; + + if (pos !== null && pos !== void 0) { + this.pos = pos; + + if (this.options.locations) { + while (this.pos < this.lineStart) { + this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1; + --this.curLine; + } + } + + this.nextToken(); + } + + if (this.end > this.start) { + message += ` ${this.input.slice(this.start, this.end)}`; + } + + this.raise(this.start, message); + } + + /* + * Esprima-FB represents JSX strings as tokens called "JSXText", but Acorn-JSX + * uses regular tt.string without any distinction between this and regular JS + * strings. As such, we intercept an attempt to read a JSX string and set a flag + * on extra so that when tokens are converted, the next token will be switched + * to JSXText via onToken. + */ + jsx_readString(quote) { // eslint-disable-line camelcase -- required by API + const result = super.jsx_readString(quote); + + if (this.type === tokTypes.string) { + this[STATE].jsxAttrValueToken = true; + } + return result; + } + + /** + * Performs last-minute Esprima-specific compatibility checks and fixes. + * @param {ASTNode} result The node to check. + * @returns {ASTNode} The finished node. + */ + [ESPRIMA_FINISH_NODE](result) { + + // Acorn doesn't count the opening and closing backticks as part of templates + // so we have to adjust ranges/locations appropriately. + if (result.type === "TemplateElement") { + + // save template element references to fix start/end later + this[STATE].templateElements.push(result); + } + + if (result.type.includes("Function") && !result.generator) { + result.generator = false; + } + + return result; + } + }; +}; + +const version$1 = "10.4.0"; + +/** + * @fileoverview Main Espree file that converts Acorn into Esprima output. + * + * This file contains code from the following MIT-licensed projects: + * 1. Acorn + * 2. Babylon + * 3. Babel-ESLint + * + * This file also contains code from Esprima, which is BSD licensed. + * + * Acorn is Copyright 2012-2015 Acorn Contributors (https://github.com/marijnh/acorn/blob/master/AUTHORS) + * Babylon is Copyright 2014-2015 various contributors (https://github.com/babel/babel/blob/master/packages/babylon/AUTHORS) + * Babel-ESLint is Copyright 2014-2015 Sebastian McKenzie + * + * 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. + * + * 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 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. + * + * Esprima is Copyright (c) jQuery Foundation, Inc. and Contributors, 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. + * + * 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 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. + */ + + +// To initialize lazily. +const parsers = { + _regular: null, + _jsx: null, + + get regular() { + if (this._regular === null) { + this._regular = acorn__namespace.Parser.extend(espree()); + } + return this._regular; + }, + + get jsx() { + if (this._jsx === null) { + this._jsx = acorn__namespace.Parser.extend(jsx__default["default"](), espree()); + } + return this._jsx; + }, + + get(options) { + const useJsx = Boolean( + options && + options.ecmaFeatures && + options.ecmaFeatures.jsx + ); + + return useJsx ? this.jsx : this.regular; + } +}; + +//------------------------------------------------------------------------------ +// Tokenizer +//------------------------------------------------------------------------------ + +/** + * Tokenizes the given code. + * @param {string} code The code to tokenize. + * @param {Object} options Options defining how to tokenize. + * @returns {Token[]} An array of tokens. + * @throws {SyntaxError} If the input code is invalid. + * @private + */ +function tokenize(code, options) { + const Parser = parsers.get(options); + + // Ensure to collect tokens. + if (!options || options.tokens !== true) { + options = Object.assign({}, options, { tokens: true }); // eslint-disable-line no-param-reassign -- stylistic choice + } + + return new Parser(options, code).tokenize(); +} + +//------------------------------------------------------------------------------ +// Parser +//------------------------------------------------------------------------------ + +/** + * Parses the given code. + * @param {string} code The code to tokenize. + * @param {Object} options Options defining how to tokenize. + * @returns {ASTNode} The "Program" AST node. + * @throws {SyntaxError} If the input code is invalid. + */ +function parse(code, options) { + const Parser = parsers.get(options); + + return new Parser(options, code).parse(); +} + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +const version = version$1; +const name = "espree"; + +/* istanbul ignore next */ +const VisitorKeys = (function() { + return visitorKeys__namespace.KEYS; +}()); + +// Derive node types from VisitorKeys +/* istanbul ignore next */ +const Syntax = (function() { + let key, + types = {}; + + if (typeof Object.create === "function") { + types = Object.create(null); + } + + for (key in VisitorKeys) { + if (Object.hasOwn(VisitorKeys, key)) { + types[key] = key; + } + } + + if (typeof Object.freeze === "function") { + Object.freeze(types); + } + + return types; +}()); + +const latestEcmaVersion = getLatestEcmaVersion(); + +const supportedEcmaVersions = getSupportedEcmaVersions(); + +exports.Syntax = Syntax; +exports.VisitorKeys = VisitorKeys; +exports.latestEcmaVersion = latestEcmaVersion; +exports.name = name; +exports.parse = parse; +exports.supportedEcmaVersions = supportedEcmaVersions; +exports.tokenize = tokenize; +exports.version = version; diff --git a/node_modules/espree/espree.js b/node_modules/espree/espree.js new file mode 100644 index 0000000000000000000000000000000000000000..15e0ce52b02617cd279244b890286df7a28447b7 --- /dev/null +++ b/node_modules/espree/espree.js @@ -0,0 +1,174 @@ +/** + * @fileoverview Main Espree file that converts Acorn into Esprima output. + * + * This file contains code from the following MIT-licensed projects: + * 1. Acorn + * 2. Babylon + * 3. Babel-ESLint + * + * This file also contains code from Esprima, which is BSD licensed. + * + * Acorn is Copyright 2012-2015 Acorn Contributors (https://github.com/marijnh/acorn/blob/master/AUTHORS) + * Babylon is Copyright 2014-2015 various contributors (https://github.com/babel/babel/blob/master/packages/babylon/AUTHORS) + * Babel-ESLint is Copyright 2014-2015 Sebastian McKenzie + * + * 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. + * + * 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 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. + * + * Esprima is Copyright (c) jQuery Foundation, Inc. and Contributors, 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. + * + * 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 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. + */ + + +import * as acorn from "acorn"; +import jsx from "acorn-jsx"; +import espree from "./lib/espree.js"; +import espreeVersion from "./lib/version.js"; +import * as visitorKeys from "eslint-visitor-keys"; +import { getLatestEcmaVersion, getSupportedEcmaVersions } from "./lib/options.js"; + + +// To initialize lazily. +const parsers = { + _regular: null, + _jsx: null, + + get regular() { + if (this._regular === null) { + this._regular = acorn.Parser.extend(espree()); + } + return this._regular; + }, + + get jsx() { + if (this._jsx === null) { + this._jsx = acorn.Parser.extend(jsx(), espree()); + } + return this._jsx; + }, + + get(options) { + const useJsx = Boolean( + options && + options.ecmaFeatures && + options.ecmaFeatures.jsx + ); + + return useJsx ? this.jsx : this.regular; + } +}; + +//------------------------------------------------------------------------------ +// Tokenizer +//------------------------------------------------------------------------------ + +/** + * Tokenizes the given code. + * @param {string} code The code to tokenize. + * @param {Object} options Options defining how to tokenize. + * @returns {Token[]} An array of tokens. + * @throws {SyntaxError} If the input code is invalid. + * @private + */ +export function tokenize(code, options) { + const Parser = parsers.get(options); + + // Ensure to collect tokens. + if (!options || options.tokens !== true) { + options = Object.assign({}, options, { tokens: true }); // eslint-disable-line no-param-reassign -- stylistic choice + } + + return new Parser(options, code).tokenize(); +} + +//------------------------------------------------------------------------------ +// Parser +//------------------------------------------------------------------------------ + +/** + * Parses the given code. + * @param {string} code The code to tokenize. + * @param {Object} options Options defining how to tokenize. + * @returns {ASTNode} The "Program" AST node. + * @throws {SyntaxError} If the input code is invalid. + */ +export function parse(code, options) { + const Parser = parsers.get(options); + + return new Parser(options, code).parse(); +} + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +export const version = espreeVersion; +export const name = "espree"; + +/* istanbul ignore next */ +export const VisitorKeys = (function() { + return visitorKeys.KEYS; +}()); + +// Derive node types from VisitorKeys +/* istanbul ignore next */ +export const Syntax = (function() { + let key, + types = {}; + + if (typeof Object.create === "function") { + types = Object.create(null); + } + + for (key in VisitorKeys) { + if (Object.hasOwn(VisitorKeys, key)) { + types[key] = key; + } + } + + if (typeof Object.freeze === "function") { + Object.freeze(types); + } + + return types; +}()); + +export const latestEcmaVersion = getLatestEcmaVersion(); + +export const supportedEcmaVersions = getSupportedEcmaVersions(); diff --git a/node_modules/espree/lib/espree.js b/node_modules/espree/lib/espree.js new file mode 100644 index 0000000000000000000000000000000000000000..2be1b56d30df906650850b41dae43d8d44efb078 --- /dev/null +++ b/node_modules/espree/lib/espree.js @@ -0,0 +1,349 @@ +/* eslint no-param-reassign: 0 -- stylistic choice */ + +import TokenTranslator from "./token-translator.js"; +import { normalizeOptions } from "./options.js"; + + +const STATE = Symbol("espree's internal state"); +const ESPRIMA_FINISH_NODE = Symbol("espree's esprimaFinishNode"); + + +/** + * Converts an Acorn comment to a Esprima comment. + * @param {boolean} block True if it's a block comment, false if not. + * @param {string} text The text of the comment. + * @param {int} start The index at which the comment starts. + * @param {int} end The index at which the comment ends. + * @param {Location} startLoc The location at which the comment starts. + * @param {Location} endLoc The location at which the comment ends. + * @param {string} code The source code being parsed. + * @returns {Object} The comment object. + * @private + */ +function convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc, code) { + let type; + + if (block) { + type = "Block"; + } else if (code.slice(start, start + 2) === "#!") { + type = "Hashbang"; + } else { + type = "Line"; + } + + const comment = { + type, + value: text + }; + + if (typeof start === "number") { + comment.start = start; + comment.end = end; + comment.range = [start, end]; + } + + if (typeof startLoc === "object") { + comment.loc = { + start: startLoc, + end: endLoc + }; + } + + return comment; +} + +export default () => Parser => { + const tokTypes = Object.assign({}, Parser.acorn.tokTypes); + + if (Parser.acornJsx) { + Object.assign(tokTypes, Parser.acornJsx.tokTypes); + } + + return class Espree extends Parser { + constructor(opts, code) { + if (typeof opts !== "object" || opts === null) { + opts = {}; + } + if (typeof code !== "string" && !(code instanceof String)) { + code = String(code); + } + + // save original source type in case of commonjs + const originalSourceType = opts.sourceType; + const options = normalizeOptions(opts); + const ecmaFeatures = options.ecmaFeatures || {}; + const tokenTranslator = + options.tokens === true + ? new TokenTranslator(tokTypes, code) + : null; + + /* + * Data that is unique to Espree and is not represented internally + * in Acorn. + * + * For ES2023 hashbangs, Espree will call `onComment()` during the + * constructor, so we must define state before having access to + * `this`. + */ + const state = { + originalSourceType: originalSourceType || options.sourceType, + tokens: tokenTranslator ? [] : null, + comments: options.comment === true ? [] : null, + impliedStrict: ecmaFeatures.impliedStrict === true && options.ecmaVersion >= 5, + ecmaVersion: options.ecmaVersion, + jsxAttrValueToken: false, + lastToken: null, + templateElements: [] + }; + + // Initialize acorn parser. + super({ + + // do not use spread, because we don't want to pass any unknown options to acorn + ecmaVersion: options.ecmaVersion, + sourceType: options.sourceType, + ranges: options.ranges, + locations: options.locations, + allowReserved: options.allowReserved, + + // Truthy value is true for backward compatibility. + allowReturnOutsideFunction: options.allowReturnOutsideFunction, + + // Collect tokens + onToken(token) { + if (tokenTranslator) { + + // Use `tokens`, `ecmaVersion`, and `jsxAttrValueToken` in the state. + tokenTranslator.onToken(token, state); + } + if (token.type !== tokTypes.eof) { + state.lastToken = token; + } + }, + + // Collect comments + onComment(block, text, start, end, startLoc, endLoc) { + if (state.comments) { + const comment = convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc, code); + + state.comments.push(comment); + } + } + }, code); + + /* + * We put all of this data into a symbol property as a way to avoid + * potential naming conflicts with future versions of Acorn. + */ + this[STATE] = state; + } + + tokenize() { + do { + this.next(); + } while (this.type !== tokTypes.eof); + + // Consume the final eof token + this.next(); + + const extra = this[STATE]; + const tokens = extra.tokens; + + if (extra.comments) { + tokens.comments = extra.comments; + } + + return tokens; + } + + finishNode(...args) { + const result = super.finishNode(...args); + + return this[ESPRIMA_FINISH_NODE](result); + } + + finishNodeAt(...args) { + const result = super.finishNodeAt(...args); + + return this[ESPRIMA_FINISH_NODE](result); + } + + parse() { + const extra = this[STATE]; + const program = super.parse(); + + program.sourceType = extra.originalSourceType; + + if (extra.comments) { + program.comments = extra.comments; + } + if (extra.tokens) { + program.tokens = extra.tokens; + } + + /* + * Adjust opening and closing position of program to match Esprima. + * Acorn always starts programs at range 0 whereas Esprima starts at the + * first AST node's start (the only real difference is when there's leading + * whitespace or leading comments). Acorn also counts trailing whitespace + * as part of the program whereas Esprima only counts up to the last token. + */ + if (program.body.length) { + const [firstNode] = program.body; + + if (program.range) { + program.range[0] = firstNode.range[0]; + } + if (program.loc) { + program.loc.start = firstNode.loc.start; + } + program.start = firstNode.start; + } + if (extra.lastToken) { + if (program.range) { + program.range[1] = extra.lastToken.range[1]; + } + if (program.loc) { + program.loc.end = extra.lastToken.loc.end; + } + program.end = extra.lastToken.end; + } + + + /* + * https://github.com/eslint/espree/issues/349 + * Ensure that template elements have correct range information. + * This is one location where Acorn produces a different value + * for its start and end properties vs. the values present in the + * range property. In order to avoid confusion, we set the start + * and end properties to the values that are present in range. + * This is done here, instead of in finishNode(), because Acorn + * uses the values of start and end internally while parsing, making + * it dangerous to change those values while parsing is ongoing. + * By waiting until the end of parsing, we can safely change these + * values without affect any other part of the process. + */ + this[STATE].templateElements.forEach(templateElement => { + const startOffset = -1; + const endOffset = templateElement.tail ? 1 : 2; + + templateElement.start += startOffset; + templateElement.end += endOffset; + + if (templateElement.range) { + templateElement.range[0] += startOffset; + templateElement.range[1] += endOffset; + } + + if (templateElement.loc) { + templateElement.loc.start.column += startOffset; + templateElement.loc.end.column += endOffset; + } + }); + + return program; + } + + parseTopLevel(node) { + if (this[STATE].impliedStrict) { + this.strict = true; + } + return super.parseTopLevel(node); + } + + /** + * Overwrites the default raise method to throw Esprima-style errors. + * @param {int} pos The position of the error. + * @param {string} message The error message. + * @throws {SyntaxError} A syntax error. + * @returns {void} + */ + raise(pos, message) { + const loc = Parser.acorn.getLineInfo(this.input, pos); + const err = new SyntaxError(message); + + err.index = pos; + err.lineNumber = loc.line; + err.column = loc.column + 1; // acorn uses 0-based columns + throw err; + } + + /** + * Overwrites the default raise method to throw Esprima-style errors. + * @param {int} pos The position of the error. + * @param {string} message The error message. + * @throws {SyntaxError} A syntax error. + * @returns {void} + */ + raiseRecoverable(pos, message) { + this.raise(pos, message); + } + + /** + * Overwrites the default unexpected method to throw Esprima-style errors. + * @param {int} pos The position of the error. + * @throws {SyntaxError} A syntax error. + * @returns {void} + */ + unexpected(pos) { + let message = "Unexpected token"; + + if (pos !== null && pos !== void 0) { + this.pos = pos; + + if (this.options.locations) { + while (this.pos < this.lineStart) { + this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1; + --this.curLine; + } + } + + this.nextToken(); + } + + if (this.end > this.start) { + message += ` ${this.input.slice(this.start, this.end)}`; + } + + this.raise(this.start, message); + } + + /* + * Esprima-FB represents JSX strings as tokens called "JSXText", but Acorn-JSX + * uses regular tt.string without any distinction between this and regular JS + * strings. As such, we intercept an attempt to read a JSX string and set a flag + * on extra so that when tokens are converted, the next token will be switched + * to JSXText via onToken. + */ + jsx_readString(quote) { // eslint-disable-line camelcase -- required by API + const result = super.jsx_readString(quote); + + if (this.type === tokTypes.string) { + this[STATE].jsxAttrValueToken = true; + } + return result; + } + + /** + * Performs last-minute Esprima-specific compatibility checks and fixes. + * @param {ASTNode} result The node to check. + * @returns {ASTNode} The finished node. + */ + [ESPRIMA_FINISH_NODE](result) { + + // Acorn doesn't count the opening and closing backticks as part of templates + // so we have to adjust ranges/locations appropriately. + if (result.type === "TemplateElement") { + + // save template element references to fix start/end later + this[STATE].templateElements.push(result); + } + + if (result.type.includes("Function") && !result.generator) { + result.generator = false; + } + + return result; + } + }; +}; diff --git a/node_modules/espree/lib/features.js b/node_modules/espree/lib/features.js new file mode 100644 index 0000000000000000000000000000000000000000..31467d288fb053c9d6d72f562d75af97c23f2f5c --- /dev/null +++ b/node_modules/espree/lib/features.js @@ -0,0 +1,27 @@ +/** + * @fileoverview The list of feature flags supported by the parser and their default + * settings. + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +// None! + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +export default { + + // React JSX parsing + jsx: false, + + // allow return statement in global scope + globalReturn: false, + + // allow implied strict mode + impliedStrict: false +}; diff --git a/node_modules/espree/lib/options.js b/node_modules/espree/lib/options.js new file mode 100644 index 0000000000000000000000000000000000000000..85bb9029fe0a9fc4f4971bce92e30c4fdef73345 --- /dev/null +++ b/node_modules/espree/lib/options.js @@ -0,0 +1,125 @@ +/** + * @fileoverview A collection of methods for processing Espree's options. + * @author Kai Cataldo + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const SUPPORTED_VERSIONS = [ + 3, + 5, + 6, // 2015 + 7, // 2016 + 8, // 2017 + 9, // 2018 + 10, // 2019 + 11, // 2020 + 12, // 2021 + 13, // 2022 + 14, // 2023 + 15, // 2024 + 16, // 2025 + 17 // 2026 +]; + +/** + * Get the latest ECMAScript version supported by Espree. + * @returns {number} The latest ECMAScript version. + */ +export function getLatestEcmaVersion() { + return SUPPORTED_VERSIONS.at(-1); +} + +/** + * Get the list of ECMAScript versions supported by Espree. + * @returns {number[]} An array containing the supported ECMAScript versions. + */ +export function getSupportedEcmaVersions() { + return [...SUPPORTED_VERSIONS]; +} + +/** + * Normalize ECMAScript version from the initial config + * @param {(number|"latest")} ecmaVersion ECMAScript version from the initial config + * @throws {Error} throws an error if the ecmaVersion is invalid. + * @returns {number} normalized ECMAScript version + */ +function normalizeEcmaVersion(ecmaVersion = 5) { + + let version = ecmaVersion === "latest" ? getLatestEcmaVersion() : ecmaVersion; + + if (typeof version !== "number") { + throw new Error(`ecmaVersion must be a number or "latest". Received value of type ${typeof ecmaVersion} instead.`); + } + + // Calculate ECMAScript edition number from official year version starting with + // ES2015, which corresponds with ES6 (or a difference of 2009). + if (version >= 2015) { + version -= 2009; + } + + if (!SUPPORTED_VERSIONS.includes(version)) { + throw new Error("Invalid ecmaVersion."); + } + + return version; +} + +/** + * Normalize sourceType from the initial config + * @param {string} sourceType to normalize + * @throws {Error} throw an error if sourceType is invalid + * @returns {string} normalized sourceType + */ +function normalizeSourceType(sourceType = "script") { + if (sourceType === "script" || sourceType === "module") { + return sourceType; + } + + if (sourceType === "commonjs") { + return "script"; + } + + throw new Error("Invalid sourceType."); +} + +/** + * Normalize parserOptions + * @param {Object} options the parser options to normalize + * @throws {Error} throw an error if found invalid option. + * @returns {Object} normalized options + */ +export function normalizeOptions(options) { + const ecmaVersion = normalizeEcmaVersion(options.ecmaVersion); + const sourceType = normalizeSourceType(options.sourceType); + const ranges = options.range === true; + const locations = options.loc === true; + + if (ecmaVersion !== 3 && options.allowReserved) { + + // a value of `false` is intentionally allowed here, so a shared config can overwrite it when needed + throw new Error("`allowReserved` is only supported when ecmaVersion is 3"); + } + if (typeof options.allowReserved !== "undefined" && typeof options.allowReserved !== "boolean") { + throw new Error("`allowReserved`, when present, must be `true` or `false`"); + } + const allowReserved = ecmaVersion === 3 ? (options.allowReserved || "never") : false; + const ecmaFeatures = options.ecmaFeatures || {}; + const allowReturnOutsideFunction = options.sourceType === "commonjs" || + Boolean(ecmaFeatures.globalReturn); + + if (sourceType === "module" && ecmaVersion < 6) { + throw new Error("sourceType 'module' is not supported when ecmaVersion < 2015. Consider adding `{ ecmaVersion: 2015 }` to the parser options."); + } + + return Object.assign({}, options, { + ecmaVersion, + sourceType, + ranges, + locations, + allowReserved, + allowReturnOutsideFunction + }); +} diff --git a/node_modules/espree/lib/token-translator.js b/node_modules/espree/lib/token-translator.js new file mode 100644 index 0000000000000000000000000000000000000000..6daf865a3f7ff360e501f82ee62c12f8d6cfaedb --- /dev/null +++ b/node_modules/espree/lib/token-translator.js @@ -0,0 +1,263 @@ +/** + * @fileoverview Translates tokens between Acorn format and Esprima format. + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +// none! + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + + +// Esprima Token Types +const Token = { + Boolean: "Boolean", + EOF: "", + Identifier: "Identifier", + PrivateIdentifier: "PrivateIdentifier", + Keyword: "Keyword", + Null: "Null", + Numeric: "Numeric", + Punctuator: "Punctuator", + String: "String", + RegularExpression: "RegularExpression", + Template: "Template", + JSXIdentifier: "JSXIdentifier", + JSXText: "JSXText" +}; + +/** + * Converts part of a template into an Esprima token. + * @param {AcornToken[]} tokens The Acorn tokens representing the template. + * @param {string} code The source code. + * @returns {EsprimaToken} The Esprima equivalent of the template token. + * @private + */ +function convertTemplatePart(tokens, code) { + const firstToken = tokens[0], + lastTemplateToken = tokens.at(-1); + + const token = { + type: Token.Template, + value: code.slice(firstToken.start, lastTemplateToken.end) + }; + + if (firstToken.loc) { + token.loc = { + start: firstToken.loc.start, + end: lastTemplateToken.loc.end + }; + } + + if (firstToken.range) { + token.start = firstToken.range[0]; + token.end = lastTemplateToken.range[1]; + token.range = [token.start, token.end]; + } + + return token; +} + +/** + * Contains logic to translate Acorn tokens into Esprima tokens. + * @param {Object} acornTokTypes The Acorn token types. + * @param {string} code The source code Acorn is parsing. This is necessary + * to correct the "value" property of some tokens. + * @constructor + */ +function TokenTranslator(acornTokTypes, code) { + + // token types + this._acornTokTypes = acornTokTypes; + + // token buffer for templates + this._tokens = []; + + // track the last curly brace + this._curlyBrace = null; + + // the source code + this._code = code; + +} + +TokenTranslator.prototype = { + constructor: TokenTranslator, + + /** + * Translates a single Esprima token to a single Acorn token. This may be + * inaccurate due to how templates are handled differently in Esprima and + * Acorn, but should be accurate for all other tokens. + * @param {AcornToken} token The Acorn token to translate. + * @param {Object} extra Espree extra object. + * @returns {EsprimaToken} The Esprima version of the token. + */ + translate(token, extra) { + + const type = token.type, + tt = this._acornTokTypes; + + if (type === tt.name) { + token.type = Token.Identifier; + + // TODO: See if this is an Acorn bug + if (token.value === "static") { + token.type = Token.Keyword; + } + + if (extra.ecmaVersion > 5 && (token.value === "yield" || token.value === "let")) { + token.type = Token.Keyword; + } + + } else if (type === tt.privateId) { + token.type = Token.PrivateIdentifier; + + } else if (type === tt.semi || type === tt.comma || + type === tt.parenL || type === tt.parenR || + type === tt.braceL || type === tt.braceR || + type === tt.dot || type === tt.bracketL || + type === tt.colon || type === tt.question || + type === tt.bracketR || type === tt.ellipsis || + type === tt.arrow || type === tt.jsxTagStart || + type === tt.incDec || type === tt.starstar || + type === tt.jsxTagEnd || type === tt.prefix || + type === tt.questionDot || + (type.binop && !type.keyword) || + type.isAssign) { + + token.type = Token.Punctuator; + token.value = this._code.slice(token.start, token.end); + } else if (type === tt.jsxName) { + token.type = Token.JSXIdentifier; + } else if (type.label === "jsxText" || type === tt.jsxAttrValueToken) { + token.type = Token.JSXText; + } else if (type.keyword) { + if (type.keyword === "true" || type.keyword === "false") { + token.type = Token.Boolean; + } else if (type.keyword === "null") { + token.type = Token.Null; + } else { + token.type = Token.Keyword; + } + } else if (type === tt.num) { + token.type = Token.Numeric; + token.value = this._code.slice(token.start, token.end); + } else if (type === tt.string) { + + if (extra.jsxAttrValueToken) { + extra.jsxAttrValueToken = false; + token.type = Token.JSXText; + } else { + token.type = Token.String; + } + + token.value = this._code.slice(token.start, token.end); + } else if (type === tt.regexp) { + token.type = Token.RegularExpression; + const value = token.value; + + token.regex = { + flags: value.flags, + pattern: value.pattern + }; + token.value = `/${value.pattern}/${value.flags}`; + } + + return token; + }, + + /** + * Function to call during Acorn's onToken handler. + * @param {AcornToken} token The Acorn token. + * @param {Object} extra The Espree extra object. + * @returns {void} + */ + onToken(token, extra) { + + const tt = this._acornTokTypes, + tokens = extra.tokens, + templateTokens = this._tokens; + + /** + * Flushes the buffered template tokens and resets the template + * tracking. + * @returns {void} + * @private + */ + const translateTemplateTokens = () => { + tokens.push(convertTemplatePart(this._tokens, this._code)); + this._tokens = []; + }; + + if (token.type === tt.eof) { + + // might be one last curlyBrace + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + } + + return; + } + + if (token.type === tt.backQuote) { + + // if there's already a curly, it's not part of the template + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + this._curlyBrace = null; + } + + templateTokens.push(token); + + // it's the end + if (templateTokens.length > 1) { + translateTemplateTokens(); + } + + return; + } + if (token.type === tt.dollarBraceL) { + templateTokens.push(token); + translateTemplateTokens(); + return; + } + if (token.type === tt.braceR) { + + // if there's already a curly, it's not part of the template + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + } + + // store new curly for later + this._curlyBrace = token; + return; + } + if (token.type === tt.template || token.type === tt.invalidTemplate) { + if (this._curlyBrace) { + templateTokens.push(this._curlyBrace); + this._curlyBrace = null; + } + + templateTokens.push(token); + return; + } + + if (this._curlyBrace) { + tokens.push(this.translate(this._curlyBrace, extra)); + this._curlyBrace = null; + } + + tokens.push(this.translate(token, extra)); + } +}; + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +export default TokenTranslator; diff --git a/node_modules/espree/lib/version.js b/node_modules/espree/lib/version.js new file mode 100644 index 0000000000000000000000000000000000000000..26f3eced6da787c4e624b4b681d1125875ef9ec2 --- /dev/null +++ b/node_modules/espree/lib/version.js @@ -0,0 +1,3 @@ +const version = "10.4.0"; + +export default version; diff --git a/node_modules/espree/package.json b/node_modules/espree/package.json new file mode 100644 index 0000000000000000000000000000000000000000..20b6dc6f2f386db197aa83bd1e484185269405b4 --- /dev/null +++ b/node_modules/espree/package.json @@ -0,0 +1,77 @@ +{ + "name": "espree", + "description": "An Esprima-compatible JavaScript parser built on Acorn", + "author": "Nicholas C. Zakas ", + "homepage": "https://github.com/eslint/js/blob/main/packages/espree/README.md", + "main": "dist/espree.cjs", + "type": "module", + "exports": { + ".": [ + { + "import": "./espree.js", + "require": "./dist/espree.cjs", + "default": "./dist/espree.cjs" + }, + "./dist/espree.cjs" + ], + "./package.json": "./package.json" + }, + "version": "10.4.0", + "files": [ + "lib", + "dist/espree.cjs", + "espree.js" + ], + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/eslint/js.git", + "directory": "packages/espree" + }, + "bugs": { + "url": "https://github.com/eslint/js/issues" + }, + "funding": "https://opencollective.com/eslint", + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.15.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^4.2.1" + }, + "devDependencies": { + "@rollup/plugin-commonjs": "^28.0.0", + "@rollup/plugin-json": "^6.1.0", + "@rollup/plugin-node-resolve": "^15.3.0", + "eslint-release": "^3.2.0", + "esprima-fb": "^8001.2001.0-dev-harmony-fb", + "npm-run-all2": "^6.2.2", + "rollup": "^2.79.1", + "shelljs": "^0.8.5" + }, + "keywords": [ + "ast", + "ecmascript", + "javascript", + "parser", + "syntax", + "acorn" + ], + "scripts": { + "build": "rollup -c rollup.config.js", + "build:debug": "npm run build -- -m", + "build:docs": "node tools/sync-docs.js", + "build:update-version": "node tools/update-version.js", + "prepublishOnly": "npm run build:update-version && npm run build", + "pretest": "npm run build", + "release:generate:latest": "eslint-generate-release", + "release:generate:alpha": "eslint-generate-prerelease alpha", + "release:generate:beta": "eslint-generate-prerelease beta", + "release:generate:rc": "eslint-generate-prerelease rc", + "release:publish": "eslint-publish-release", + "test": "npm-run-all -s test:*", + "test:cjs": "mocha --color --reporter progress --timeout 30000 tests/lib/commonjs.cjs", + "test:esm": "c8 mocha --color --reporter progress --timeout 30000 tests/lib/**/*.js" + } +} diff --git a/node_modules/esquery/README.md b/node_modules/esquery/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6d5c39fda84e6e654033aca4f9acb54e54b8ea27 --- /dev/null +++ b/node_modules/esquery/README.md @@ -0,0 +1,27 @@ +ESQuery is a library for querying the AST output by Esprima for patterns of syntax using a CSS style selector system. Check out the demo: + +[demo](https://estools.github.io/esquery/) + +The following selectors are supported: +* AST node type: `ForStatement` +* [wildcard](http://dev.w3.org/csswg/selectors4/#universal-selector): `*` +* [attribute existence](http://dev.w3.org/csswg/selectors4/#attribute-selectors): `[attr]` +* [attribute value](http://dev.w3.org/csswg/selectors4/#attribute-selectors): `[attr="foo"]` or `[attr=123]` +* attribute regex: `[attr=/foo.*/]` or (with flags) `[attr=/foo.*/is]` +* attribute conditions: `[attr!="foo"]`, `[attr>2]`, `[attr<3]`, `[attr>=2]`, or `[attr<=3]` +* nested attribute: `[attr.level2="foo"]` +* field: `FunctionDeclaration > Identifier.id` +* [First](http://dev.w3.org/csswg/selectors4/#the-first-child-pseudo) or [last](http://dev.w3.org/csswg/selectors4/#the-last-child-pseudo) child: `:first-child` or `:last-child` +* [nth-child](http://dev.w3.org/csswg/selectors4/#the-nth-child-pseudo) (no ax+b support): `:nth-child(2)` +* [nth-last-child](http://dev.w3.org/csswg/selectors4/#the-nth-last-child-pseudo) (no ax+b support): `:nth-last-child(1)` +* [descendant](http://dev.w3.org/csswg/selectors4/#descendant-combinators): `ancestor descendant` +* [child](http://dev.w3.org/csswg/selectors4/#child-combinators): `parent > child` +* [following sibling](http://dev.w3.org/csswg/selectors4/#general-sibling-combinators): `node ~ sibling` +* [adjacent sibling](http://dev.w3.org/csswg/selectors4/#adjacent-sibling-combinators): `node + adjacent` +* [negation](http://dev.w3.org/csswg/selectors4/#negation-pseudo): `:not(ForStatement)` +* [has](https://drafts.csswg.org/selectors-4/#has-pseudo): `:has(ForStatement)`, `:has(> ForStatement)` +* [matches-any](http://dev.w3.org/csswg/selectors4/#matches): `:is([attr] > :first-child, :last-child)` +* [subject indicator](http://dev.w3.org/csswg/selectors4/#subject): `!IfStatement > [name="foo"]` +* class of AST node: `:statement`, `:expression`, `:declaration`, `:function`, or `:pattern` + +[![Build Status](https://travis-ci.org/estools/esquery.png?branch=master)](https://travis-ci.org/estools/esquery) diff --git a/node_modules/esquery/dist/esquery.esm.js b/node_modules/esquery/dist/esquery.esm.js new file mode 100644 index 0000000000000000000000000000000000000000..70191dfa9f09326f94df55669c99a6808015768f --- /dev/null +++ b/node_modules/esquery/dist/esquery.esm.js @@ -0,0 +1,4418 @@ +function _arrayLikeToArray(r, a) { + (null == a || a > r.length) && (a = r.length); + for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; + return n; +} +function _arrayWithHoles(r) { + if (Array.isArray(r)) return r; +} +function _arrayWithoutHoles(r) { + if (Array.isArray(r)) return _arrayLikeToArray(r); +} +function _iterableToArray(r) { + if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); +} +function _iterableToArrayLimit(r, l) { + var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; + if (null != t) { + var e, + n, + i, + u, + a = [], + f = !0, + o = !1; + try { + if (i = (t = t.call(r)).next, 0 === l) { + if (Object(t) !== t) return; + f = !1; + } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); + } catch (r) { + o = !0, n = r; + } finally { + try { + if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; + } finally { + if (o) throw n; + } + } + return a; + } +} +function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} +function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} +function _slicedToArray(r, e) { + return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); +} +function _toConsumableArray(r) { + return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); +} +function _typeof(o) { + "@babel/helpers - typeof"; + + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { + return typeof o; + } : function (o) { + return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; + }, _typeof(o); +} +function _unsupportedIterableToArray(r, a) { + if (r) { + if ("string" == typeof r) return _arrayLikeToArray(r, a); + var t = {}.toString.call(r).slice(8, -1); + return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; + } +} + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +var estraverse = createCommonjsModule(function (module, exports) { + /* + Copyright (C) 2012-2013 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat + + 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. + + 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 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. + */ + /*jslint vars:false, bitwise:true*/ + /*jshint indent:4*/ + /*global exports:true*/ + (function clone(exports) { + + var Syntax, VisitorOption, VisitorKeys, BREAK, SKIP, REMOVE; + function deepCopy(obj) { + var ret = {}, + key, + val; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + val = obj[key]; + if (typeof val === 'object' && val !== null) { + ret[key] = deepCopy(val); + } else { + ret[key] = val; + } + } + } + return ret; + } + + // based on LLVM libc++ upper_bound / lower_bound + // MIT License + + function upperBound(array, func) { + var diff, len, i, current; + len = array.length; + i = 0; + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + len = diff; + } else { + i = current + 1; + len -= diff + 1; + } + } + return i; + } + Syntax = { + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AwaitExpression: 'AwaitExpression', + // CAUTION: It's deferred to ES7. + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ChainExpression: 'ChainExpression', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ComprehensionBlock: 'ComprehensionBlock', + // CAUTION: It's deferred to ES7. + ComprehensionExpression: 'ComprehensionExpression', + // CAUTION: It's deferred to ES7. + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DebuggerStatement: 'DebuggerStatement', + DirectiveStatement: 'DirectiveStatement', + DoWhileStatement: 'DoWhileStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + ForOfStatement: 'ForOfStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + GeneratorExpression: 'GeneratorExpression', + // CAUTION: It's deferred to ES7. + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportExpression: 'ImportExpression', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MetaProperty: 'MetaProperty', + MethodDefinition: 'MethodDefinition', + ModuleSpecifier: 'ModuleSpecifier', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + PrivateIdentifier: 'PrivateIdentifier', + Program: 'Program', + Property: 'Property', + PropertyDefinition: 'PropertyDefinition', + RestElement: 'RestElement', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + Super: 'Super', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; + VisitorKeys = { + AssignmentExpression: ['left', 'right'], + AssignmentPattern: ['left', 'right'], + ArrayExpression: ['elements'], + ArrayPattern: ['elements'], + ArrowFunctionExpression: ['params', 'body'], + AwaitExpression: ['argument'], + // CAUTION: It's deferred to ES7. + BlockStatement: ['body'], + BinaryExpression: ['left', 'right'], + BreakStatement: ['label'], + CallExpression: ['callee', 'arguments'], + CatchClause: ['param', 'body'], + ChainExpression: ['expression'], + ClassBody: ['body'], + ClassDeclaration: ['id', 'superClass', 'body'], + ClassExpression: ['id', 'superClass', 'body'], + ComprehensionBlock: ['left', 'right'], + // CAUTION: It's deferred to ES7. + ComprehensionExpression: ['blocks', 'filter', 'body'], + // CAUTION: It's deferred to ES7. + ConditionalExpression: ['test', 'consequent', 'alternate'], + ContinueStatement: ['label'], + DebuggerStatement: [], + DirectiveStatement: [], + DoWhileStatement: ['body', 'test'], + EmptyStatement: [], + ExportAllDeclaration: ['source'], + ExportDefaultDeclaration: ['declaration'], + ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], + ExportSpecifier: ['exported', 'local'], + ExpressionStatement: ['expression'], + ForStatement: ['init', 'test', 'update', 'body'], + ForInStatement: ['left', 'right', 'body'], + ForOfStatement: ['left', 'right', 'body'], + FunctionDeclaration: ['id', 'params', 'body'], + FunctionExpression: ['id', 'params', 'body'], + GeneratorExpression: ['blocks', 'filter', 'body'], + // CAUTION: It's deferred to ES7. + Identifier: [], + IfStatement: ['test', 'consequent', 'alternate'], + ImportExpression: ['source'], + ImportDeclaration: ['specifiers', 'source'], + ImportDefaultSpecifier: ['local'], + ImportNamespaceSpecifier: ['local'], + ImportSpecifier: ['imported', 'local'], + Literal: [], + LabeledStatement: ['label', 'body'], + LogicalExpression: ['left', 'right'], + MemberExpression: ['object', 'property'], + MetaProperty: ['meta', 'property'], + MethodDefinition: ['key', 'value'], + ModuleSpecifier: [], + NewExpression: ['callee', 'arguments'], + ObjectExpression: ['properties'], + ObjectPattern: ['properties'], + PrivateIdentifier: [], + Program: ['body'], + Property: ['key', 'value'], + PropertyDefinition: ['key', 'value'], + RestElement: ['argument'], + ReturnStatement: ['argument'], + SequenceExpression: ['expressions'], + SpreadElement: ['argument'], + Super: [], + SwitchStatement: ['discriminant', 'cases'], + SwitchCase: ['test', 'consequent'], + TaggedTemplateExpression: ['tag', 'quasi'], + TemplateElement: [], + TemplateLiteral: ['quasis', 'expressions'], + ThisExpression: [], + ThrowStatement: ['argument'], + TryStatement: ['block', 'handler', 'finalizer'], + UnaryExpression: ['argument'], + UpdateExpression: ['argument'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + WhileStatement: ['test', 'body'], + WithStatement: ['object', 'body'], + YieldExpression: ['argument'] + }; + + // unique id + BREAK = {}; + SKIP = {}; + REMOVE = {}; + VisitorOption = { + Break: BREAK, + Skip: SKIP, + Remove: REMOVE + }; + function Reference(parent, key) { + this.parent = parent; + this.key = key; + } + Reference.prototype.replace = function replace(node) { + this.parent[this.key] = node; + }; + Reference.prototype.remove = function remove() { + if (Array.isArray(this.parent)) { + this.parent.splice(this.key, 1); + return true; + } else { + this.replace(null); + return false; + } + }; + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } + function Controller() {} + + // API: + // return property path array from root to current node + Controller.prototype.path = function path() { + var i, iz, j, jz, result, element; + function addToPath(result, path) { + if (Array.isArray(path)) { + for (j = 0, jz = path.length; j < jz; ++j) { + result.push(path[j]); + } + } else { + result.push(path); + } + } + + // root node + if (!this.__current.path) { + return null; + } + + // first node is sentinel, second node is root element + result = []; + for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { + element = this.__leavelist[i]; + addToPath(result, element.path); + } + addToPath(result, this.__current.path); + return result; + }; + + // API: + // return type of current node + Controller.prototype.type = function () { + var node = this.current(); + return node.type || this.__current.wrap; + }; + + // API: + // return array of parent elements + Controller.prototype.parents = function parents() { + var i, iz, result; + + // first node is sentinel + result = []; + for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { + result.push(this.__leavelist[i].node); + } + return result; + }; + + // API: + // return current node + Controller.prototype.current = function current() { + return this.__current.node; + }; + Controller.prototype.__execute = function __execute(callback, element) { + var previous, result; + result = undefined; + previous = this.__current; + this.__current = element; + this.__state = null; + if (callback) { + result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); + } + this.__current = previous; + return result; + }; + + // API: + // notify control skip / break + Controller.prototype.notify = function notify(flag) { + this.__state = flag; + }; + + // API: + // skip child nodes of current node + Controller.prototype.skip = function () { + this.notify(SKIP); + }; + + // API: + // break traversals + Controller.prototype['break'] = function () { + this.notify(BREAK); + }; + + // API: + // remove node + Controller.prototype.remove = function () { + this.notify(REMOVE); + }; + Controller.prototype.__initialize = function (root, visitor) { + this.visitor = visitor; + this.root = root; + this.__worklist = []; + this.__leavelist = []; + this.__current = null; + this.__state = null; + this.__fallback = null; + if (visitor.fallback === 'iteration') { + this.__fallback = Object.keys; + } else if (typeof visitor.fallback === 'function') { + this.__fallback = visitor.fallback; + } + this.__keys = VisitorKeys; + if (visitor.keys) { + this.__keys = Object.assign(Object.create(this.__keys), visitor.keys); + } + }; + function isNode(node) { + if (node == null) { + return false; + } + return typeof node === 'object' && typeof node.type === 'string'; + } + function isProperty(nodeType, key) { + return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; + } + function candidateExistsInLeaveList(leavelist, candidate) { + for (var i = leavelist.length - 1; i >= 0; --i) { + if (leavelist[i].node === candidate) { + return true; + } + } + return false; + } + Controller.prototype.traverse = function traverse(root, visitor) { + var worklist, leavelist, element, node, nodeType, ret, key, current, current2, candidates, candidate, sentinel; + this.__initialize(root, visitor); + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + worklist.push(new Element(root, null, null, null)); + leavelist.push(new Element(null, null, null, null)); + while (worklist.length) { + element = worklist.pop(); + if (element === sentinel) { + element = leavelist.pop(); + ret = this.__execute(visitor.leave, element); + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } + if (element.node) { + ret = this.__execute(visitor.enter, element); + if (this.__state === BREAK || ret === BREAK) { + return; + } + worklist.push(sentinel); + leavelist.push(element); + if (this.__state === SKIP || ret === SKIP) { + continue; + } + node = element.node; + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (candidateExistsInLeaveList(leavelist, candidate[current2])) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', null); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, null); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + if (candidateExistsInLeaveList(leavelist, candidate)) { + continue; + } + worklist.push(new Element(candidate, key, null, null)); + } + } + } + } + }; + Controller.prototype.replace = function replace(root, visitor) { + var worklist, leavelist, node, nodeType, target, element, current, current2, candidates, candidate, sentinel, outer, key; + function removeElem(element) { + var i, key, nextElem, parent; + if (element.ref.remove()) { + // When the reference is an element of an array. + key = element.ref.key; + parent = element.ref.parent; + + // If removed from array, then decrease following items' keys. + i = worklist.length; + while (i--) { + nextElem = worklist[i]; + if (nextElem.ref && nextElem.ref.parent === parent) { + if (nextElem.ref.key < key) { + break; + } + --nextElem.ref.key; + } + } + } + } + this.__initialize(root, visitor); + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + outer = { + root: root + }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); + while (worklist.length) { + element = worklist.pop(); + if (element === sentinel) { + element = leavelist.pop(); + target = this.__execute(visitor.leave, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + } + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + } + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + continue; + } + target = this.__execute(visitor.enter, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + element.node = target; + } + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + element.node = null; + } + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + + // node may be null + node = element.node; + if (!node) { + continue; + } + worklist.push(sentinel); + leavelist.push(element); + if (this.__state === SKIP || target === SKIP) { + continue; + } + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, new Reference(node, key))); + } + } + } + return outer.root; + }; + function traverse(root, visitor) { + var controller = new Controller(); + return controller.traverse(root, visitor); + } + function replace(root, visitor) { + var controller = new Controller(); + return controller.replace(root, visitor); + } + function extendCommentRange(comment, tokens) { + var target; + target = upperBound(tokens, function search(token) { + return token.range[0] > comment.range[0]; + }); + comment.extendedRange = [comment.range[0], comment.range[1]]; + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } + return comment; + } + function attachComments(tree, providedComments, tokens) { + // At first, we should calculate extended comment ranges. + var comments = [], + comment, + len, + i, + cursor; + if (!tree.range) { + throw new Error('attachComments needs range information'); + } + + // tokens array is empty, we attach comments to tree as 'leadingComments' + if (!tokens.length) { + if (providedComments.length) { + for (i = 0, len = providedComments.length; i < len; i += 1) { + comment = deepCopy(providedComments[i]); + comment.extendedRange = [0, tree.range[0]]; + comments.push(comment); + } + tree.leadingComments = comments; + } + return tree; + } + for (i = 0, len = providedComments.length; i < len; i += 1) { + comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); + } + + // This is based on John Freeman's implementation. + cursor = 0; + traverse(tree, { + enter: function (node) { + var comment; + while (cursor < comments.length) { + comment = comments[cursor]; + if (comment.extendedRange[1] > node.range[0]) { + break; + } + if (comment.extendedRange[1] === node.range[0]) { + if (!node.leadingComments) { + node.leadingComments = []; + } + node.leadingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + cursor = 0; + traverse(tree, { + leave: function (node) { + var comment; + while (cursor < comments.length) { + comment = comments[cursor]; + if (node.range[1] < comment.extendedRange[0]) { + break; + } + if (node.range[1] === comment.extendedRange[0]) { + if (!node.trailingComments) { + node.trailingComments = []; + } + node.trailingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + return tree; + } + exports.Syntax = Syntax; + exports.traverse = traverse; + exports.replace = replace; + exports.attachComments = attachComments; + exports.VisitorKeys = VisitorKeys; + exports.VisitorOption = VisitorOption; + exports.Controller = Controller; + exports.cloneEnvironment = function () { + return clone({}); + }; + return exports; + })(exports); + /* vim: set sw=4 ts=4 et tw=80 : */ +}); + +var parser = createCommonjsModule(function (module) { + /* + * Generated by PEG.js 0.10.0. + * + * http://pegjs.org/ + */ + (function (root, factory) { + if ( module.exports) { + module.exports = factory(); + } + })(commonjsGlobal, function () { + + function peg$subclass(child, parent) { + function ctor() { + this.constructor = child; + } + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + } + function peg$SyntaxError(message, expected, found, location) { + this.message = message; + this.expected = expected; + this.found = found; + this.location = location; + this.name = "SyntaxError"; + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, peg$SyntaxError); + } + } + peg$subclass(peg$SyntaxError, Error); + peg$SyntaxError.buildMessage = function (expected, found) { + var DESCRIBE_EXPECTATION_FNS = { + literal: function literal(expectation) { + return "\"" + literalEscape(expectation.text) + "\""; + }, + "class": function _class(expectation) { + var escapedParts = "", + i; + for (i = 0; i < expectation.parts.length; i++) { + escapedParts += expectation.parts[i] instanceof Array ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) : classEscape(expectation.parts[i]); + } + return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; + }, + any: function any(expectation) { + return "any character"; + }, + end: function end(expectation) { + return "end of input"; + }, + other: function other(expectation) { + return expectation.description; + } + }; + function hex(ch) { + return ch.charCodeAt(0).toString(16).toUpperCase(); + } + function literalEscape(s) { + return s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\0/g, '\\0').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/[\x00-\x0F]/g, function (ch) { + return '\\x0' + hex(ch); + }).replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { + return '\\x' + hex(ch); + }); + } + function classEscape(s) { + return s.replace(/\\/g, '\\\\').replace(/\]/g, '\\]').replace(/\^/g, '\\^').replace(/-/g, '\\-').replace(/\0/g, '\\0').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/[\x00-\x0F]/g, function (ch) { + return '\\x0' + hex(ch); + }).replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { + return '\\x' + hex(ch); + }); + } + function describeExpectation(expectation) { + return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); + } + function describeExpected(expected) { + var descriptions = new Array(expected.length), + i, + j; + for (i = 0; i < expected.length; i++) { + descriptions[i] = describeExpectation(expected[i]); + } + descriptions.sort(); + if (descriptions.length > 0) { + for (i = 1, j = 1; i < descriptions.length; i++) { + if (descriptions[i - 1] !== descriptions[i]) { + descriptions[j] = descriptions[i]; + j++; + } + } + descriptions.length = j; + } + switch (descriptions.length) { + case 1: + return descriptions[0]; + case 2: + return descriptions[0] + " or " + descriptions[1]; + default: + return descriptions.slice(0, -1).join(", ") + ", or " + descriptions[descriptions.length - 1]; + } + } + function describeFound(found) { + return found ? "\"" + literalEscape(found) + "\"" : "end of input"; + } + return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; + }; + function peg$parse(input, options) { + options = options !== void 0 ? options : {}; + var peg$FAILED = {}, + peg$startRuleFunctions = { + start: peg$parsestart + }, + peg$startRuleFunction = peg$parsestart, + peg$c0 = function peg$c0(ss) { + return ss.length === 1 ? ss[0] : { + type: 'matches', + selectors: ss + }; + }, + peg$c1 = function peg$c1() { + return void 0; + }, + peg$c2 = " ", + peg$c3 = peg$literalExpectation(" ", false), + peg$c4 = /^[^ [\],():#!=><~+.]/, + peg$c5 = peg$classExpectation([" ", "[", "]", ",", "(", ")", ":", "#", "!", "=", ">", "<", "~", "+", "."], true, false), + peg$c6 = function peg$c6(i) { + return i.join(''); + }, + peg$c7 = ">", + peg$c8 = peg$literalExpectation(">", false), + peg$c9 = function peg$c9() { + return 'child'; + }, + peg$c10 = "~", + peg$c11 = peg$literalExpectation("~", false), + peg$c12 = function peg$c12() { + return 'sibling'; + }, + peg$c13 = "+", + peg$c14 = peg$literalExpectation("+", false), + peg$c15 = function peg$c15() { + return 'adjacent'; + }, + peg$c16 = function peg$c16() { + return 'descendant'; + }, + peg$c17 = ",", + peg$c18 = peg$literalExpectation(",", false), + peg$c19 = function peg$c19(s, ss) { + return [s].concat(ss.map(function (s) { + return s[3]; + })); + }, + peg$c20 = function peg$c20(op, s) { + if (!op) return s; + return { + type: op, + left: { + type: 'exactNode' + }, + right: s + }; + }, + peg$c21 = function peg$c21(a, ops) { + return ops.reduce(function (memo, rhs) { + return { + type: rhs[0], + left: memo, + right: rhs[1] + }; + }, a); + }, + peg$c22 = "!", + peg$c23 = peg$literalExpectation("!", false), + peg$c24 = function peg$c24(subject, as) { + var b = as.length === 1 ? as[0] : { + type: 'compound', + selectors: as + }; + if (subject) b.subject = true; + return b; + }, + peg$c25 = "*", + peg$c26 = peg$literalExpectation("*", false), + peg$c27 = function peg$c27(a) { + return { + type: 'wildcard', + value: a + }; + }, + peg$c28 = "#", + peg$c29 = peg$literalExpectation("#", false), + peg$c30 = function peg$c30(i) { + return { + type: 'identifier', + value: i + }; + }, + peg$c31 = "[", + peg$c32 = peg$literalExpectation("[", false), + peg$c33 = "]", + peg$c34 = peg$literalExpectation("]", false), + peg$c35 = function peg$c35(v) { + return v; + }, + peg$c36 = /^[>", "<", "!"], false, false), + peg$c38 = "=", + peg$c39 = peg$literalExpectation("=", false), + peg$c40 = function peg$c40(a) { + return (a || '') + '='; + }, + peg$c41 = /^[><]/, + peg$c42 = peg$classExpectation([">", "<"], false, false), + peg$c43 = ".", + peg$c44 = peg$literalExpectation(".", false), + peg$c45 = function peg$c45(a, as) { + return [].concat.apply([a], as).join(''); + }, + peg$c46 = function peg$c46(name, op, value) { + return { + type: 'attribute', + name: name, + operator: op, + value: value + }; + }, + peg$c47 = function peg$c47(name) { + return { + type: 'attribute', + name: name + }; + }, + peg$c48 = "\"", + peg$c49 = peg$literalExpectation("\"", false), + peg$c50 = /^[^\\"]/, + peg$c51 = peg$classExpectation(["\\", "\""], true, false), + peg$c52 = "\\", + peg$c53 = peg$literalExpectation("\\", false), + peg$c54 = peg$anyExpectation(), + peg$c55 = function peg$c55(a, b) { + return a + b; + }, + peg$c56 = function peg$c56(d) { + return { + type: 'literal', + value: strUnescape(d.join('')) + }; + }, + peg$c57 = "'", + peg$c58 = peg$literalExpectation("'", false), + peg$c59 = /^[^\\']/, + peg$c60 = peg$classExpectation(["\\", "'"], true, false), + peg$c61 = /^[0-9]/, + peg$c62 = peg$classExpectation([["0", "9"]], false, false), + peg$c63 = function peg$c63(a, b) { + // Can use `a.flat().join('')` once supported + var leadingDecimals = a ? [].concat.apply([], a).join('') : ''; + return { + type: 'literal', + value: parseFloat(leadingDecimals + b.join('')) + }; + }, + peg$c64 = function peg$c64(i) { + return { + type: 'literal', + value: i + }; + }, + peg$c65 = "type(", + peg$c66 = peg$literalExpectation("type(", false), + peg$c67 = /^[^ )]/, + peg$c68 = peg$classExpectation([" ", ")"], true, false), + peg$c69 = ")", + peg$c70 = peg$literalExpectation(")", false), + peg$c71 = function peg$c71(t) { + return { + type: 'type', + value: t.join('') + }; + }, + peg$c72 = /^[imsu]/, + peg$c73 = peg$classExpectation(["i", "m", "s", "u"], false, false), + peg$c74 = "/", + peg$c75 = peg$literalExpectation("/", false), + peg$c76 = function peg$c76(pattern, flgs) { + return { + type: 'regexp', + value: new RegExp(pattern.join(''), flgs ? flgs.join('') : '') + }; + }, + peg$c77 = /^[^\]\\]/, + peg$c78 = peg$classExpectation(["]", "\\"], true, false), + peg$c79 = function peg$c79(cs) { + return '[' + cs.join('') + ']'; + }, + peg$c80 = function peg$c80(a) { + return '\\' + a; + }, + peg$c81 = /^[^\/\\[]/, + peg$c82 = peg$classExpectation(["/", "\\", "["], true, false), + peg$c83 = function peg$c83(cs) { + return cs.join(''); + }, + peg$c84 = function peg$c84(i, is) { + return { + type: 'field', + name: is.reduce(function (memo, p) { + return memo + p[0] + p[1]; + }, i) + }; + }, + peg$c85 = ":not(", + peg$c86 = peg$literalExpectation(":not(", false), + peg$c87 = function peg$c87(ss) { + return { + type: 'not', + selectors: ss + }; + }, + peg$c88 = ":matches(", + peg$c89 = peg$literalExpectation(":matches(", false), + peg$c90 = function peg$c90(ss) { + return { + type: 'matches', + selectors: ss + }; + }, + peg$c91 = ":is(", + peg$c92 = peg$literalExpectation(":is(", false), + peg$c93 = ":has(", + peg$c94 = peg$literalExpectation(":has(", false), + peg$c95 = function peg$c95(ss) { + return { + type: 'has', + selectors: ss + }; + }, + peg$c96 = ":first-child", + peg$c97 = peg$literalExpectation(":first-child", false), + peg$c98 = function peg$c98() { + return nth(1); + }, + peg$c99 = ":last-child", + peg$c100 = peg$literalExpectation(":last-child", false), + peg$c101 = function peg$c101() { + return nthLast(1); + }, + peg$c102 = ":nth-child(", + peg$c103 = peg$literalExpectation(":nth-child(", false), + peg$c104 = function peg$c104(n) { + return nth(parseInt(n.join(''), 10)); + }, + peg$c105 = ":nth-last-child(", + peg$c106 = peg$literalExpectation(":nth-last-child(", false), + peg$c107 = function peg$c107(n) { + return nthLast(parseInt(n.join(''), 10)); + }, + peg$c108 = ":", + peg$c109 = peg$literalExpectation(":", false), + peg$c110 = function peg$c110(c) { + return { + type: 'class', + name: c + }; + }, + peg$currPos = 0, + peg$posDetailsCache = [{ + line: 1, + column: 1 + }], + peg$maxFailPos = 0, + peg$maxFailExpected = [], + peg$resultsCache = {}, + peg$result; + if ("startRule" in options) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); + } + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + function peg$literalExpectation(text, ignoreCase) { + return { + type: "literal", + text: text, + ignoreCase: ignoreCase + }; + } + function peg$classExpectation(parts, inverted, ignoreCase) { + return { + type: "class", + parts: parts, + inverted: inverted, + ignoreCase: ignoreCase + }; + } + function peg$anyExpectation() { + return { + type: "any" + }; + } + function peg$endExpectation() { + return { + type: "end" + }; + } + function peg$computePosDetails(pos) { + var details = peg$posDetailsCache[pos], + p; + if (details) { + return details; + } else { + p = pos - 1; + while (!peg$posDetailsCache[p]) { + p--; + } + details = peg$posDetailsCache[p]; + details = { + line: details.line, + column: details.column + }; + while (p < pos) { + if (input.charCodeAt(p) === 10) { + details.line++; + details.column = 1; + } else { + details.column++; + } + p++; + } + peg$posDetailsCache[pos] = details; + return details; + } + } + function peg$computeLocation(startPos, endPos) { + var startPosDetails = peg$computePosDetails(startPos), + endPosDetails = peg$computePosDetails(endPos); + return { + start: { + offset: startPos, + line: startPosDetails.line, + column: startPosDetails.column + }, + end: { + offset: endPos, + line: endPosDetails.line, + column: endPosDetails.column + } + }; + } + function peg$fail(expected) { + if (peg$currPos < peg$maxFailPos) { + return; + } + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; + } + peg$maxFailExpected.push(expected); + } + function peg$buildStructuredError(expected, found, location) { + return new peg$SyntaxError(peg$SyntaxError.buildMessage(expected, found), expected, found, location); + } + function peg$parsestart() { + var s0, s1, s2, s3; + var key = peg$currPos * 36 + 0, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + s2 = peg$parseselectors(); + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c0(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + s1 = peg$c1(); + } + s0 = s1; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parse_() { + var s0, s1; + var key = peg$currPos * 36 + 1, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = []; + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c3); + } + } + while (s1 !== peg$FAILED) { + s0.push(s1); + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c3); + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseidentifierName() { + var s0, s1, s2; + var key = peg$currPos * 36 + 2, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = []; + if (peg$c4.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c5); + } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + if (peg$c4.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c5); + } + } + } + } else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s1 = peg$c6(s1); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsebinaryOp() { + var s0, s1, s2, s3; + var key = peg$currPos * 36 + 3, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 62) { + s2 = peg$c7; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c8); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c9(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c10; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c11); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c12(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c13; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c14); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c15(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c3); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s1 = peg$c16(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsehasSelectors() { + var s0, s1, s2, s3, s4, s5, s6, s7; + var key = peg$currPos * 36 + 4, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parsehasSelector(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parsehasSelector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parsehasSelector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c19(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseselectors() { + var s0, s1, s2, s3, s4, s5, s6, s7; + var key = peg$currPos * 36 + 5, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseselector(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseselector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseselector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c19(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsehasSelector() { + var s0, s1, s2; + var key = peg$currPos * 36 + 6, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parsebinaryOp(); + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseselector(); + if (s2 !== peg$FAILED) { + s1 = peg$c20(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseselector() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 7, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parsesequence(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parsebinaryOp(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesequence(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parsebinaryOp(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesequence(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c21(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsesequence() { + var s0, s1, s2, s3; + var key = peg$currPos * 36 + 8, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 33) { + s1 = peg$c22; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c23); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseatom(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseatom(); + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = peg$c24(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseatom() { + var s0; + var key = peg$currPos * 36 + 9, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$parsewildcard(); + if (s0 === peg$FAILED) { + s0 = peg$parseidentifier(); + if (s0 === peg$FAILED) { + s0 = peg$parseattr(); + if (s0 === peg$FAILED) { + s0 = peg$parsefield(); + if (s0 === peg$FAILED) { + s0 = peg$parsenegation(); + if (s0 === peg$FAILED) { + s0 = peg$parsematches(); + if (s0 === peg$FAILED) { + s0 = peg$parseis(); + if (s0 === peg$FAILED) { + s0 = peg$parsehas(); + if (s0 === peg$FAILED) { + s0 = peg$parsefirstChild(); + if (s0 === peg$FAILED) { + s0 = peg$parselastChild(); + if (s0 === peg$FAILED) { + s0 = peg$parsenthChild(); + if (s0 === peg$FAILED) { + s0 = peg$parsenthLastChild(); + if (s0 === peg$FAILED) { + s0 = peg$parseclass(); + } + } + } + } + } + } + } + } + } + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsewildcard() { + var s0, s1; + var key = peg$currPos * 36 + 10, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 42) { + s1 = peg$c25; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c26); + } + } + if (s1 !== peg$FAILED) { + s1 = peg$c27(s1); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseidentifier() { + var s0, s1, s2; + var key = peg$currPos * 36 + 11, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 35) { + s1 = peg$c28; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c29); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + s1 = peg$c30(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattr() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 12, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c31; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c32); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrValue(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s5 = peg$c33; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c34); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c35(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrOps() { + var s0, s1, s2; + var key = peg$currPos * 36 + 13, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (peg$c36.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c37); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c39); + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c40(s1); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + if (peg$c41.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + { + peg$fail(peg$c42); + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrEqOps() { + var s0, s1, s2; + var key = peg$currPos * 36 + 14, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 33) { + s1 = peg$c22; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c23); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c39); + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c40(s1); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrName() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 15, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseidentifierName(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c43; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseidentifierName(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c43; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseidentifierName(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c45(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrValue() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 16, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrEqOps(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetype(); + if (s5 === peg$FAILED) { + s5 = peg$parseregex(); + } + if (s5 !== peg$FAILED) { + s1 = peg$c46(s1, s3, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrOps(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + s5 = peg$parsestring(); + if (s5 === peg$FAILED) { + s5 = peg$parsenumber(); + if (s5 === peg$FAILED) { + s5 = peg$parsepath(); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c46(s1, s3, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s1 = peg$c47(s1); + } + s0 = s1; + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsestring() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 17, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 34) { + s1 = peg$c48; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c49); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c50.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c51); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c50.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c51); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 34) { + s3 = peg$c48; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c49); + } + } + if (s3 !== peg$FAILED) { + s1 = peg$c56(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 39) { + s1 = peg$c57; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c58); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c59.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c60); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c59.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c60); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s3 = peg$c57; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c58); + } + } + if (s3 !== peg$FAILED) { + s1 = peg$c56(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenumber() { + var s0, s1, s2, s3; + var key = peg$currPos * 36 + 18, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$currPos; + s2 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s3 = peg$c43; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = peg$c63(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsepath() { + var s0, s1; + var key = peg$currPos * 36 + 19, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseidentifierName(); + if (s1 !== peg$FAILED) { + s1 = peg$c64(s1); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsetype() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 20, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c65) { + s1 = peg$c65; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c66); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c67.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c68); + } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c67.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c68); + } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c71(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseflags() { + var s0, s1; + var key = peg$currPos * 36 + 21, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = []; + if (peg$c72.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c73); + } + } + if (s1 !== peg$FAILED) { + while (s1 !== peg$FAILED) { + s0.push(s1); + if (peg$c72.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c73); + } + } + } + } else { + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseregex() { + var s0, s1, s2, s3, s4; + var key = peg$currPos * 36 + 22, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 47) { + s1 = peg$c74; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c75); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsere_character_class(); + if (s3 === peg$FAILED) { + s3 = peg$parsere_escape(); + if (s3 === peg$FAILED) { + s3 = peg$parsere_chars(); + } + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsere_character_class(); + if (s3 === peg$FAILED) { + s3 = peg$parsere_escape(); + if (s3 === peg$FAILED) { + s3 = peg$parsere_chars(); + } + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s3 = peg$c74; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c75); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseflags(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s1 = peg$c76(s2, s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsere_character_class() { + var s0, s1, s2, s3; + var key = peg$currPos * 36 + 23, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c31; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c32); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c77.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c78); + } + } + if (s3 === peg$FAILED) { + s3 = peg$parsere_escape(); + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c77.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c78); + } + } + if (s3 === peg$FAILED) { + s3 = peg$parsere_escape(); + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c33; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c34); + } + } + if (s3 !== peg$FAILED) { + s1 = peg$c79(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsere_escape() { + var s0, s1, s2; + var key = peg$currPos * 36 + 24, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s1 = peg$c52; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c80(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsere_chars() { + var s0, s1, s2; + var key = peg$currPos * 36 + 25, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = []; + if (peg$c81.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c82); + } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + if (peg$c81.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c82); + } + } + } + } else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s1 = peg$c83(s1); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsefield() { + var s0, s1, s2, s3, s4, s5, s6; + var key = peg$currPos * 36 + 26, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c43; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c43; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseidentifierName(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c43; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseidentifierName(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s1 = peg$c84(s2, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenegation() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 27, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c85) { + s1 = peg$c85; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c86); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c87(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsematches() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 28, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 9) === peg$c88) { + s1 = peg$c88; + peg$currPos += 9; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c89); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c90(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseis() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 29, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 4) === peg$c91) { + s1 = peg$c91; + peg$currPos += 4; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c92); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c90(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsehas() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 30, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c93) { + s1 = peg$c93; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c94); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parsehasSelectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c95(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsefirstChild() { + var s0, s1; + var key = peg$currPos * 36 + 31, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 12) === peg$c96) { + s1 = peg$c96; + peg$currPos += 12; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c97); + } + } + if (s1 !== peg$FAILED) { + s1 = peg$c98(); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parselastChild() { + var s0, s1; + var key = peg$currPos * 36 + 32, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c99) { + s1 = peg$c99; + peg$currPos += 11; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c100); + } + } + if (s1 !== peg$FAILED) { + s1 = peg$c101(); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenthChild() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 33, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c102) { + s1 = peg$c102; + peg$currPos += 11; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c103); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c104(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenthLastChild() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 34, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 16) === peg$c105) { + s1 = peg$c105; + peg$currPos += 16; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c106); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c107(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseclass() { + var s0, s1, s2; + var key = peg$currPos * 36 + 35, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s1 = peg$c108; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c109); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + s1 = peg$c110(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function nth(n) { + return { + type: 'nth-child', + index: { + type: 'literal', + value: n + } + }; + } + function nthLast(n) { + return { + type: 'nth-last-child', + index: { + type: 'literal', + value: n + } + }; + } + function strUnescape(s) { + return s.replace(/\\(.)/g, function (match, ch) { + switch (ch) { + case 'b': + return '\b'; + case 'f': + return '\f'; + case 'n': + return '\n'; + case 'r': + return '\r'; + case 't': + return '\t'; + case 'v': + return '\v'; + default: + return ch; + } + }); + } + peg$result = peg$startRuleFunction(); + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail(peg$endExpectation()); + } + throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)); + } + } + return { + SyntaxError: peg$SyntaxError, + parse: peg$parse + }; + }); +}); + +/** +* @typedef {"LEFT_SIDE"|"RIGHT_SIDE"} Side +*/ + +var LEFT_SIDE = 'LEFT_SIDE'; +var RIGHT_SIDE = 'RIGHT_SIDE'; + +/** + * @external AST + * @see https://esprima.readthedocs.io/en/latest/syntax-tree-format.html + */ + +/** + * One of the rules of `grammar.pegjs` + * @typedef {PlainObject} SelectorAST + * @see grammar.pegjs +*/ + +/** + * The `sequence` production of `grammar.pegjs` + * @typedef {PlainObject} SelectorSequenceAST +*/ + +/** + * Get the value of a property which may be multiple levels down + * in the object. + * @param {?PlainObject} obj + * @param {string[]} keys + * @returns {undefined|boolean|string|number|external:AST} + */ +function getPath(obj, keys) { + for (var i = 0; i < keys.length; ++i) { + if (obj == null) { + return obj; + } + obj = obj[keys[i]]; + } + return obj; +} + +/** + * Determine whether `node` can be reached by following `path`, + * starting at `ancestor`. + * @param {?external:AST} node + * @param {?external:AST} ancestor + * @param {string[]} path + * @param {Integer} fromPathIndex + * @returns {boolean} + */ +function inPath(node, ancestor, path, fromPathIndex) { + var current = ancestor; + for (var i = fromPathIndex; i < path.length; ++i) { + if (current == null) { + return false; + } + var field = current[path[i]]; + if (Array.isArray(field)) { + for (var k = 0; k < field.length; ++k) { + if (inPath(node, field[k], path, i + 1)) { + return true; + } + } + return false; + } + current = field; + } + return node === current; +} + +/** + * A generated matcher function for a selector. + * @callback SelectorMatcher + * @param {?SelectorAST} selector + * @param {external:AST[]} [ancestry=[]] + * @param {ESQueryOptions} [options] + * @returns {void} +*/ + +/** + * A WeakMap for holding cached matcher functions for selectors. + * @type {WeakMap} +*/ +var MATCHER_CACHE = typeof WeakMap === 'function' ? new WeakMap() : null; + +/** + * Look up a matcher function for `selector` in the cache. + * If it does not exist, generate it with `generateMatcher` and add it to the cache. + * In engines without WeakMap, the caching is skipped and matchers are generated with every call. + * @param {?SelectorAST} selector + * @returns {SelectorMatcher} + */ +function getMatcher(selector) { + if (selector == null) { + return function () { + return true; + }; + } + if (MATCHER_CACHE != null) { + var matcher = MATCHER_CACHE.get(selector); + if (matcher != null) { + return matcher; + } + matcher = generateMatcher(selector); + MATCHER_CACHE.set(selector, matcher); + return matcher; + } + return generateMatcher(selector); +} + +/** + * Create a matcher function for `selector`, + * @param {?SelectorAST} selector + * @returns {SelectorMatcher} + */ +function generateMatcher(selector) { + switch (selector.type) { + case 'wildcard': + return function () { + return true; + }; + case 'identifier': + { + var value = selector.value.toLowerCase(); + return function (node, ancestry, options) { + var nodeTypeKey = options && options.nodeTypeKey || 'type'; + return value === node[nodeTypeKey].toLowerCase(); + }; + } + case 'exactNode': + return function (node, ancestry) { + return ancestry.length === 0; + }; + case 'field': + { + var path = selector.name.split('.'); + return function (node, ancestry) { + var ancestor = ancestry[path.length - 1]; + return inPath(node, ancestor, path, 0); + }; + } + case 'matches': + { + var matchers = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + for (var i = 0; i < matchers.length; ++i) { + if (matchers[i](node, ancestry, options)) { + return true; + } + } + return false; + }; + } + case 'compound': + { + var _matchers = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + for (var i = 0; i < _matchers.length; ++i) { + if (!_matchers[i](node, ancestry, options)) { + return false; + } + } + return true; + }; + } + case 'not': + { + var _matchers2 = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + for (var i = 0; i < _matchers2.length; ++i) { + if (_matchers2[i](node, ancestry, options)) { + return false; + } + } + return true; + }; + } + case 'has': + { + var _matchers3 = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + var result = false; + var a = []; + estraverse.traverse(node, { + enter: function enter(node, parent) { + if (parent != null) { + a.unshift(parent); + } + for (var i = 0; i < _matchers3.length; ++i) { + if (_matchers3[i](node, a, options)) { + result = true; + this["break"](); + return; + } + } + }, + leave: function leave() { + a.shift(); + }, + keys: options && options.visitorKeys, + fallback: options && options.fallback || 'iteration' + }); + return result; + }; + } + case 'child': + { + var left = getMatcher(selector.left); + var right = getMatcher(selector.right); + return function (node, ancestry, options) { + if (ancestry.length > 0 && right(node, ancestry, options)) { + return left(ancestry[0], ancestry.slice(1), options); + } + return false; + }; + } + case 'descendant': + { + var _left = getMatcher(selector.left); + var _right = getMatcher(selector.right); + return function (node, ancestry, options) { + if (_right(node, ancestry, options)) { + for (var i = 0, l = ancestry.length; i < l; ++i) { + if (_left(ancestry[i], ancestry.slice(i + 1), options)) { + return true; + } + } + } + return false; + }; + } + case 'attribute': + { + var _path = selector.name.split('.'); + switch (selector.operator) { + case void 0: + return function (node) { + return getPath(node, _path) != null; + }; + case '=': + switch (selector.value.type) { + case 'regexp': + return function (node) { + var p = getPath(node, _path); + return typeof p === 'string' && selector.value.value.test(p); + }; + case 'literal': + { + var literal = "".concat(selector.value.value); + return function (node) { + return literal === "".concat(getPath(node, _path)); + }; + } + case 'type': + return function (node) { + return selector.value.value === _typeof(getPath(node, _path)); + }; + } + throw new Error("Unknown selector value type: ".concat(selector.value.type)); + case '!=': + switch (selector.value.type) { + case 'regexp': + return function (node) { + return !selector.value.value.test(getPath(node, _path)); + }; + case 'literal': + { + var _literal = "".concat(selector.value.value); + return function (node) { + return _literal !== "".concat(getPath(node, _path)); + }; + } + case 'type': + return function (node) { + return selector.value.value !== _typeof(getPath(node, _path)); + }; + } + throw new Error("Unknown selector value type: ".concat(selector.value.type)); + case '<=': + return function (node) { + return getPath(node, _path) <= selector.value.value; + }; + case '<': + return function (node) { + return getPath(node, _path) < selector.value.value; + }; + case '>': + return function (node) { + return getPath(node, _path) > selector.value.value; + }; + case '>=': + return function (node) { + return getPath(node, _path) >= selector.value.value; + }; + } + throw new Error("Unknown operator: ".concat(selector.operator)); + } + case 'sibling': + { + var _left2 = getMatcher(selector.left); + var _right2 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right2(node, ancestry, options) && sibling(node, _left2, ancestry, LEFT_SIDE, options) || selector.left.subject && _left2(node, ancestry, options) && sibling(node, _right2, ancestry, RIGHT_SIDE, options); + }; + } + case 'adjacent': + { + var _left3 = getMatcher(selector.left); + var _right3 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right3(node, ancestry, options) && adjacent(node, _left3, ancestry, LEFT_SIDE, options) || selector.right.subject && _left3(node, ancestry, options) && adjacent(node, _right3, ancestry, RIGHT_SIDE, options); + }; + } + case 'nth-child': + { + var nth = selector.index.value; + var _right4 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right4(node, ancestry, options) && nthChild(node, ancestry, nth, options); + }; + } + case 'nth-last-child': + { + var _nth = -selector.index.value; + var _right5 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right5(node, ancestry, options) && nthChild(node, ancestry, _nth, options); + }; + } + case 'class': + { + var name = selector.name.toLowerCase(); + return function (node, ancestry, options) { + if (options && options.matchClass) { + return options.matchClass(selector.name, node, ancestry); + } + if (options && options.nodeTypeKey) return false; + switch (name) { + case 'statement': + if (node.type.slice(-9) === 'Statement') return true; + // fallthrough: interface Declaration <: Statement { } + case 'declaration': + return node.type.slice(-11) === 'Declaration'; + case 'pattern': + if (node.type.slice(-7) === 'Pattern') return true; + // fallthrough: interface Expression <: Node, Pattern { } + case 'expression': + return node.type.slice(-10) === 'Expression' || node.type.slice(-7) === 'Literal' || node.type === 'Identifier' && (ancestry.length === 0 || ancestry[0].type !== 'MetaProperty') || node.type === 'MetaProperty'; + case 'function': + return node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression'; + } + throw new Error("Unknown class name: ".concat(selector.name)); + }; + } + } + throw new Error("Unknown selector type: ".concat(selector.type)); +} + +/** + * @callback TraverseOptionFallback + * @param {external:AST} node The given node. + * @returns {string[]} An array of visitor keys for the given node. + */ + +/** + * @callback ClassMatcher + * @param {string} className The name of the class to match. + * @param {external:AST} node The node to match against. + * @param {Array} ancestry The ancestry of the node. + * @returns {boolean} True if the node matches the class, false if not. + */ + +/** + * @typedef {object} ESQueryOptions + * @property {string} [nodeTypeKey="type"] By passing `nodeTypeKey`, we can allow other ASTs to use ESQuery. + * @property { { [nodeType: string]: string[] } } [visitorKeys] By passing `visitorKeys` mapping, we can extend the properties of the nodes that traverse the node. + * @property {TraverseOptionFallback} [fallback] By passing `fallback` option, we can control the properties of traversing nodes when encountering unknown nodes. + * @property {ClassMatcher} [matchClass] By passing `matchClass` option, we can customize the interpretation of classes. + */ + +/** + * Given a `node` and its ancestors, determine if `node` is matched + * by `selector`. + * @param {?external:AST} node + * @param {?SelectorAST} selector + * @param {external:AST[]} [ancestry=[]] + * @param {ESQueryOptions} [options] + * @throws {Error} Unknowns (operator, class name, selector type, or + * selector value type) + * @returns {boolean} + */ +function matches(node, selector, ancestry, options) { + if (!selector) { + return true; + } + if (!node) { + return false; + } + if (!ancestry) { + ancestry = []; + } + return getMatcher(selector)(node, ancestry, options); +} + +/** + * Get visitor keys of a given node. + * @param {external:AST} node The AST node to get keys. + * @param {ESQueryOptions|undefined} options + * @returns {string[]} Visitor keys of the node. + */ +function getVisitorKeys(node, options) { + var nodeTypeKey = options && options.nodeTypeKey || 'type'; + var nodeType = node[nodeTypeKey]; + if (options && options.visitorKeys && options.visitorKeys[nodeType]) { + return options.visitorKeys[nodeType]; + } + if (estraverse.VisitorKeys[nodeType]) { + return estraverse.VisitorKeys[nodeType]; + } + if (options && typeof options.fallback === 'function') { + return options.fallback(node); + } + // 'iteration' fallback + return Object.keys(node).filter(function (key) { + return key !== nodeTypeKey; + }); +} + +/** + * Check whether the given value is an ASTNode or not. + * @param {any} node The value to check. + * @param {ESQueryOptions|undefined} options The options to use. + * @returns {boolean} `true` if the value is an ASTNode. + */ +function isNode(node, options) { + var nodeTypeKey = options && options.nodeTypeKey || 'type'; + return node !== null && _typeof(node) === 'object' && typeof node[nodeTypeKey] === 'string'; +} + +/** + * Determines if the given node has a sibling that matches the + * given selector matcher. + * @param {external:AST} node + * @param {SelectorMatcher} matcher + * @param {external:AST[]} ancestry + * @param {Side} side + * @param {ESQueryOptions|undefined} options + * @returns {boolean} + */ +function sibling(node, matcher, ancestry, side, options) { + var _ancestry = _slicedToArray(ancestry, 1), + parent = _ancestry[0]; + if (!parent) { + return false; + } + var keys = getVisitorKeys(parent, options); + for (var i = 0; i < keys.length; ++i) { + var listProp = parent[keys[i]]; + if (Array.isArray(listProp)) { + var startIndex = listProp.indexOf(node); + if (startIndex < 0) { + continue; + } + var lowerBound = void 0, + upperBound = void 0; + if (side === LEFT_SIDE) { + lowerBound = 0; + upperBound = startIndex; + } else { + lowerBound = startIndex + 1; + upperBound = listProp.length; + } + for (var k = lowerBound; k < upperBound; ++k) { + if (isNode(listProp[k], options) && matcher(listProp[k], ancestry, options)) { + return true; + } + } + } + } + return false; +} + +/** + * Determines if the given node has an adjacent sibling that matches + * the given selector matcher. + * @param {external:AST} node + * @param {SelectorMatcher} matcher + * @param {external:AST[]} ancestry + * @param {Side} side + * @param {ESQueryOptions|undefined} options + * @returns {boolean} + */ +function adjacent(node, matcher, ancestry, side, options) { + var _ancestry2 = _slicedToArray(ancestry, 1), + parent = _ancestry2[0]; + if (!parent) { + return false; + } + var keys = getVisitorKeys(parent, options); + for (var i = 0; i < keys.length; ++i) { + var listProp = parent[keys[i]]; + if (Array.isArray(listProp)) { + var idx = listProp.indexOf(node); + if (idx < 0) { + continue; + } + if (side === LEFT_SIDE && idx > 0 && isNode(listProp[idx - 1], options) && matcher(listProp[idx - 1], ancestry, options)) { + return true; + } + if (side === RIGHT_SIDE && idx < listProp.length - 1 && isNode(listProp[idx + 1], options) && matcher(listProp[idx + 1], ancestry, options)) { + return true; + } + } + } + return false; +} + +/** + * Determines if the given node is the `nth` child. + * If `nth` is negative then the position is counted + * from the end of the list of children. + * @param {external:AST} node + * @param {external:AST[]} ancestry + * @param {Integer} nth + * @param {ESQueryOptions|undefined} options + * @returns {boolean} + */ +function nthChild(node, ancestry, nth, options) { + if (nth === 0) { + return false; + } + var _ancestry3 = _slicedToArray(ancestry, 1), + parent = _ancestry3[0]; + if (!parent) { + return false; + } + var keys = getVisitorKeys(parent, options); + for (var i = 0; i < keys.length; ++i) { + var listProp = parent[keys[i]]; + if (Array.isArray(listProp)) { + var idx = nth < 0 ? listProp.length + nth : nth - 1; + if (idx >= 0 && idx < listProp.length && listProp[idx] === node) { + return true; + } + } + } + return false; +} + +/** + * For each selector node marked as a subject, find the portion of the + * selector that the subject must match. + * @param {SelectorAST} selector + * @param {SelectorAST} [ancestor] Defaults to `selector` + * @returns {SelectorAST[]} + */ +function subjects(selector, ancestor) { + if (selector == null || _typeof(selector) != 'object') { + return []; + } + if (ancestor == null) { + ancestor = selector; + } + var results = selector.subject ? [ancestor] : []; + var keys = Object.keys(selector); + for (var i = 0; i < keys.length; ++i) { + var p = keys[i]; + var sel = selector[p]; + results.push.apply(results, _toConsumableArray(subjects(sel, p === 'left' ? sel : ancestor))); + } + return results; +} + +/** +* @callback TraverseVisitor +* @param {?external:AST} node +* @param {?external:AST} parent +* @param {external:AST[]} ancestry +*/ + +/** + * From a JS AST and a selector AST, collect all JS AST nodes that + * match the selector. + * @param {external:AST} ast + * @param {?SelectorAST} selector + * @param {TraverseVisitor} visitor + * @param {ESQueryOptions} [options] + * @returns {external:AST[]} + */ +function traverse(ast, selector, visitor, options) { + if (!selector) { + return; + } + var ancestry = []; + var matcher = getMatcher(selector); + var altSubjects = subjects(selector).map(getMatcher); + estraverse.traverse(ast, { + enter: function enter(node, parent) { + if (parent != null) { + ancestry.unshift(parent); + } + if (matcher(node, ancestry, options)) { + if (altSubjects.length) { + for (var i = 0, l = altSubjects.length; i < l; ++i) { + if (altSubjects[i](node, ancestry, options)) { + visitor(node, parent, ancestry); + } + for (var k = 0, m = ancestry.length; k < m; ++k) { + var succeedingAncestry = ancestry.slice(k + 1); + if (altSubjects[i](ancestry[k], succeedingAncestry, options)) { + visitor(ancestry[k], parent, succeedingAncestry); + } + } + } + } else { + visitor(node, parent, ancestry); + } + } + }, + leave: function leave() { + ancestry.shift(); + }, + keys: options && options.visitorKeys, + fallback: options && options.fallback || 'iteration' + }); +} + +/** + * From a JS AST and a selector AST, collect all JS AST nodes that + * match the selector. + * @param {external:AST} ast + * @param {?SelectorAST} selector + * @param {ESQueryOptions} [options] + * @returns {external:AST[]} + */ +function match(ast, selector, options) { + var results = []; + traverse(ast, selector, function (node) { + results.push(node); + }, options); + return results; +} + +/** + * Parse a selector string and return its AST. + * @param {string} selector + * @returns {SelectorAST} + */ +function parse(selector) { + return parser.parse(selector); +} + +/** + * Query the code AST using the selector string. + * @param {external:AST} ast + * @param {string} selector + * @param {ESQueryOptions} [options] + * @returns {external:AST[]} + */ +function query(ast, selector, options) { + return match(ast, parse(selector), options); +} +query.parse = parse; +query.match = match; +query.traverse = traverse; +query.matches = matches; +query.query = query; + +export default query; diff --git a/node_modules/esquery/dist/esquery.esm.min.js b/node_modules/esquery/dist/esquery.esm.min.js new file mode 100644 index 0000000000000000000000000000000000000000..39861882d4298fdc6029168c2a31fa9c52ed88ce --- /dev/null +++ b/node_modules/esquery/dist/esquery.esm.min.js @@ -0,0 +1,2 @@ +function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r=0;--r)if(e[r].node===t)return!0;return!1}function d(e,t){return(new f).traverse(e,t)}function m(e,t){var r;return r=function(e,t){var r,n,o,a;for(n=e.length,o=0;n;)t(e[a=o+(r=n>>>1)])?n=r:(o=a+1,n-=r+1);return o}(t,(function(t){return t.range[0]>e.range[0]})),e.extendedRange=[e.range[0],e.range[1]],r!==t.length&&(e.extendedRange[1]=t[r].range[0]),(r-=1)>=0&&(e.extendedRange[0]=t[r].range[1]),e}return r={AssignmentExpression:"AssignmentExpression",AssignmentPattern:"AssignmentPattern",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ChainExpression:"ChainExpression",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportAllDeclaration:"ExportAllDeclaration",ExportDefaultDeclaration:"ExportDefaultDeclaration",ExportNamedDeclaration:"ExportNamedDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportExpression:"ImportExpression",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MetaProperty:"MetaProperty",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",PrivateIdentifier:"PrivateIdentifier",Program:"Program",Property:"Property",PropertyDefinition:"PropertyDefinition",RestElement:"RestElement",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",Super:"Super",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"},o={AssignmentExpression:["left","right"],AssignmentPattern:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","body"],AwaitExpression:["argument"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ChainExpression:["expression"],ClassBody:["body"],ClassDeclaration:["id","superClass","body"],ClassExpression:["id","superClass","body"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportAllDeclaration:["source"],ExportDefaultDeclaration:["declaration"],ExportNamedDeclaration:["declaration","specifiers","source"],ExportSpecifier:["exported","local"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","body"],FunctionExpression:["id","params","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportExpression:["source"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["local"],ImportNamespaceSpecifier:["local"],ImportSpecifier:["imported","local"],Literal:[],LabeledStatement:["label","body"],LogicalExpression:["left","right"],MemberExpression:["object","property"],MetaProperty:["meta","property"],MethodDefinition:["key","value"],ModuleSpecifier:[],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],PrivateIdentifier:[],Program:["body"],Property:["key","value"],PropertyDefinition:["key","value"],RestElement:["argument"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],Super:[],SwitchStatement:["discriminant","cases"],SwitchCase:["test","consequent"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handler","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"]},n={Break:a={},Skip:i={},Remove:s={}},l.prototype.replace=function(e){this.parent[this.key]=e},l.prototype.remove=function(){return Array.isArray(this.parent)?(this.parent.splice(this.key,1),!0):(this.replace(null),!1)},f.prototype.path=function(){var e,t,r,n,o;function a(e,t){if(Array.isArray(t))for(r=0,n=t.length;r=0;)if(v=s[f=x[d]])if(Array.isArray(v)){for(m=v.length;(m-=1)>=0;)if(v[m]&&!y(n,v[m])){if(h(u,x[d]))o=new c(v[m],[f,m],"Property",null);else{if(!p(v[m]))continue;o=new c(v[m],[f,m],null,null)}r.push(o)}}else if(p(v)){if(y(n,v))continue;r.push(new c(v,f,null,null))}}}else if(o=n.pop(),l=this.__execute(t.leave,o),this.__state===a||l===a)return},f.prototype.replace=function(e,t){var r,n,o,u,f,y,d,m,x,v,g,A,E;function b(e){var t,n,o,a;if(e.ref.remove())for(n=e.ref.key,a=e.ref.parent,t=r.length;t--;)if((o=r[t]).ref&&o.ref.parent===a){if(o.ref.key=0;)if(v=o[E=x[d]])if(Array.isArray(v)){for(m=v.length;(m-=1)>=0;)if(v[m]){if(h(u,x[d]))y=new c(v[m],[E,m],"Property",new l(v,m));else{if(!p(v[m]))continue;y=new c(v[m],[E,m],null,new l(v,m))}r.push(y)}}else p(v)&&r.push(new c(v,E,null,new l(o,E)))}}else if(y=n.pop(),void 0!==(f=this.__execute(t.leave,y))&&f!==a&&f!==i&&f!==s&&y.ref.replace(f),this.__state!==s&&f!==s||b(y),this.__state===a||f===a)return A.root;return A.root},t.Syntax=r,t.traverse=d,t.replace=function(e,t){return(new f).replace(e,t)},t.attachComments=function(e,t,r){var o,a,i,s,l=[];if(!e.range)throw new Error("attachComments needs range information");if(!r.length){if(t.length){for(i=0,a=t.length;ie.range[0]);)t.extendedRange[1]===e.range[0]?(e.leadingComments||(e.leadingComments=[]),e.leadingComments.push(t),l.splice(s,1)):s+=1;return s===l.length?n.Break:l[s].extendedRange[0]>e.range[1]?n.Skip:void 0}}),s=0,d(e,{leave:function(e){for(var t;se.range[1]?n.Skip:void 0}}),e},t.VisitorKeys=o,t.VisitorOption=n,t.Controller=f,t.cloneEnvironment=function(){return e({})},t}(t)})),s=a((function(e){e.exports&&(e.exports=function(){function e(t,r,n,o){this.message=t,this.expected=r,this.found=n,this.location=o,this.name="SyntaxError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,e)}return function(e,t){function r(){this.constructor=e}r.prototype=t.prototype,e.prototype=new r}(e,Error),e.buildMessage=function(e,t){var r={literal:function(e){return'"'+o(e.text)+'"'},class:function(e){var t,r="";for(t=0;t0){for(t=1,n=1;t<~+.]/,p=me([" ","[","]",",","(",")",":","#","!","=",">","<","~","+","."],!0,!1),h=de(">",!1),y=de("~",!1),d=de("+",!1),m=de(",",!1),x=function(e,t){return[e].concat(t.map((function(e){return e[3]})))},v=de("!",!1),g=de("*",!1),A=de("#",!1),E=de("[",!1),b=de("]",!1),S=/^[>","<","!"],!1,!1),C=de("=",!1),P=function(e){return(e||"")+"="},w=/^[><]/,k=me([">","<"],!1,!1),D=de(".",!1),I=function(e,t,r){return{type:"attribute",name:e,operator:t,value:r}},j=de('"',!1),T=/^[^\\"]/,F=me(["\\",'"'],!0,!1),R=de("\\",!1),O={type:"any"},L=function(e,t){return e+t},M=function(e){return{type:"literal",value:(t=e.join(""),t.replace(/\\(.)/g,(function(e,t){switch(t){case"b":return"\b";case"f":return"\f";case"n":return"\n";case"r":return"\r";case"t":return"\t";case"v":return"\v";default:return t}})))};var t},B=de("'",!1),U=/^[^\\']/,K=me(["\\","'"],!0,!1),N=/^[0-9]/,W=me([["0","9"]],!1,!1),V=de("type(",!1),q=/^[^ )]/,G=me([" ",")"],!0,!1),z=de(")",!1),H=/^[imsu]/,Y=me(["i","m","s","u"],!1,!1),$=de("/",!1),J=/^[^\]\\]/,Q=me(["]","\\"],!0,!1),X=/^[^\/\\[]/,Z=me(["/","\\","["],!0,!1),ee=de(":not(",!1),te=de(":matches(",!1),re=function(e){return{type:"matches",selectors:e}},ne=de(":is(",!1),oe=de(":has(",!1),ae=de(":first-child",!1),ie=de(":last-child",!1),se=de(":nth-child(",!1),ue=de(":nth-last-child(",!1),le=de(":",!1),ce=0,fe=[{line:1,column:1}],pe=0,he=[],ye={};if("startRule"in r){if(!(r.startRule in u))throw new Error("Can't start parsing from rule \""+r.startRule+'".');l=u[r.startRule]}function de(e,t){return{type:"literal",text:e,ignoreCase:t}}function me(e,t,r){return{type:"class",parts:e,inverted:t,ignoreCase:r}}function xe(e){var r,n=fe[e];if(n)return n;for(r=e-1;!fe[r];)r--;for(n={line:(n=fe[r]).line,column:n.column};rpe&&(pe=ce,he=[]),he.push(e))}function Ae(){var e,t,r,n,o=36*ce+0,a=ye[o];return a?(ce=a.nextPos,a.result):(e=ce,(t=Ee())!==s&&(r=_e())!==s&&Ee()!==s?e=t=1===(n=r).length?n[0]:{type:"matches",selectors:n}:(ce=e,e=s),e===s&&(e=ce,(t=Ee())!==s&&(t=void 0),e=t),ye[o]={nextPos:ce,result:e},e)}function Ee(){var e,r,n=36*ce+1,o=ye[n];if(o)return ce=o.nextPos,o.result;for(e=[],32===t.charCodeAt(ce)?(r=" ",ce++):(r=s,ge(c));r!==s;)e.push(r),32===t.charCodeAt(ce)?(r=" ",ce++):(r=s,ge(c));return ye[n]={nextPos:ce,result:e},e}function be(){var e,r,n,o=36*ce+2,a=ye[o];if(a)return ce=a.nextPos,a.result;if(r=[],f.test(t.charAt(ce))?(n=t.charAt(ce),ce++):(n=s,ge(p)),n!==s)for(;n!==s;)r.push(n),f.test(t.charAt(ce))?(n=t.charAt(ce),ce++):(n=s,ge(p));else r=s;return r!==s&&(r=r.join("")),e=r,ye[o]={nextPos:ce,result:e},e}function Se(){var e,r,n,o=36*ce+3,a=ye[o];return a?(ce=a.nextPos,a.result):(e=ce,(r=Ee())!==s?(62===t.charCodeAt(ce)?(n=">",ce++):(n=s,ge(h)),n!==s&&Ee()!==s?e=r="child":(ce=e,e=s)):(ce=e,e=s),e===s&&(e=ce,(r=Ee())!==s?(126===t.charCodeAt(ce)?(n="~",ce++):(n=s,ge(y)),n!==s&&Ee()!==s?e=r="sibling":(ce=e,e=s)):(ce=e,e=s),e===s&&(e=ce,(r=Ee())!==s?(43===t.charCodeAt(ce)?(n="+",ce++):(n=s,ge(d)),n!==s&&Ee()!==s?e=r="adjacent":(ce=e,e=s)):(ce=e,e=s),e===s&&(e=ce,32===t.charCodeAt(ce)?(r=" ",ce++):(r=s,ge(c)),r!==s&&(n=Ee())!==s?e=r="descendant":(ce=e,e=s)))),ye[o]={nextPos:ce,result:e},e)}function _e(){var e,r,n,o,a,i,u,l,c=36*ce+5,f=ye[c];if(f)return ce=f.nextPos,f.result;if(e=ce,(r=Pe())!==s){for(n=[],o=ce,(a=Ee())!==s?(44===t.charCodeAt(ce)?(i=",",ce++):(i=s,ge(m)),i!==s&&(u=Ee())!==s&&(l=Pe())!==s?o=a=[a,i,u,l]:(ce=o,o=s)):(ce=o,o=s);o!==s;)n.push(o),o=ce,(a=Ee())!==s?(44===t.charCodeAt(ce)?(i=",",ce++):(i=s,ge(m)),i!==s&&(u=Ee())!==s&&(l=Pe())!==s?o=a=[a,i,u,l]:(ce=o,o=s)):(ce=o,o=s);n!==s?e=r=x(r,n):(ce=e,e=s)}else ce=e,e=s;return ye[c]={nextPos:ce,result:e},e}function Ce(){var e,t,r,n,o,a=36*ce+6,i=ye[a];return i?(ce=i.nextPos,i.result):(e=ce,(t=Se())===s&&(t=null),t!==s&&(r=Pe())!==s?(o=r,e=t=(n=t)?{type:n,left:{type:"exactNode"},right:o}:o):(ce=e,e=s),ye[a]={nextPos:ce,result:e},e)}function Pe(){var e,t,r,n,o,a,i,u=36*ce+7,l=ye[u];if(l)return ce=l.nextPos,l.result;if(e=ce,(t=we())!==s){for(r=[],n=ce,(o=Se())!==s&&(a=we())!==s?n=o=[o,a]:(ce=n,n=s);n!==s;)r.push(n),n=ce,(o=Se())!==s&&(a=we())!==s?n=o=[o,a]:(ce=n,n=s);r!==s?(i=t,e=t=r.reduce((function(e,t){return{type:t[0],left:e,right:t[1]}}),i)):(ce=e,e=s)}else ce=e,e=s;return ye[u]={nextPos:ce,result:e},e}function we(){var e,r,n,o,a,i,u,l=36*ce+8,c=ye[l];if(c)return ce=c.nextPos,c.result;if(e=ce,33===t.charCodeAt(ce)?(r="!",ce++):(r=s,ge(v)),r===s&&(r=null),r!==s){if(n=[],(o=ke())!==s)for(;o!==s;)n.push(o),o=ke();else n=s;n!==s?(a=r,u=1===(i=n).length?i[0]:{type:"compound",selectors:i},a&&(u.subject=!0),e=r=u):(ce=e,e=s)}else ce=e,e=s;return ye[l]={nextPos:ce,result:e},e}function ke(){var e,r=36*ce+9,n=ye[r];return n?(ce=n.nextPos,n.result):((e=function(){var e,r,n=36*ce+10,o=ye[n];return o?(ce=o.nextPos,o.result):(42===t.charCodeAt(ce)?(r="*",ce++):(r=s,ge(g)),r!==s&&(r={type:"wildcard",value:r}),e=r,ye[n]={nextPos:ce,result:e},e)}())===s&&(e=function(){var e,r,n,o=36*ce+11,a=ye[o];return a?(ce=a.nextPos,a.result):(e=ce,35===t.charCodeAt(ce)?(r="#",ce++):(r=s,ge(A)),r===s&&(r=null),r!==s&&(n=be())!==s?e=r={type:"identifier",value:n}:(ce=e,e=s),ye[o]={nextPos:ce,result:e},e)}())===s&&(e=function(){var e,r,n,o,a=36*ce+12,i=ye[a];return i?(ce=i.nextPos,i.result):(e=ce,91===t.charCodeAt(ce)?(r="[",ce++):(r=s,ge(E)),r!==s&&Ee()!==s&&(n=function(){var e,r,n,o,a=36*ce+16,i=ye[a];return i?(ce=i.nextPos,i.result):(e=ce,(r=De())!==s&&Ee()!==s&&(n=function(){var e,r,n,o=36*ce+14,a=ye[o];return a?(ce=a.nextPos,a.result):(e=ce,33===t.charCodeAt(ce)?(r="!",ce++):(r=s,ge(v)),r===s&&(r=null),r!==s?(61===t.charCodeAt(ce)?(n="=",ce++):(n=s,ge(C)),n!==s?(r=P(r),e=r):(ce=e,e=s)):(ce=e,e=s),ye[o]={nextPos:ce,result:e},e)}())!==s&&Ee()!==s?((o=function(){var e,r,n,o,a,i=36*ce+20,u=ye[i];if(u)return ce=u.nextPos,u.result;if(e=ce,"type("===t.substr(ce,5)?(r="type(",ce+=5):(r=s,ge(V)),r!==s)if(Ee()!==s){if(n=[],q.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(G)),o!==s)for(;o!==s;)n.push(o),q.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(G));else n=s;n!==s&&(o=Ee())!==s?(41===t.charCodeAt(ce)?(a=")",ce++):(a=s,ge(z)),a!==s?(r={type:"type",value:n.join("")},e=r):(ce=e,e=s)):(ce=e,e=s)}else ce=e,e=s;else ce=e,e=s;return ye[i]={nextPos:ce,result:e},e}())===s&&(o=function(){var e,r,n,o,a,i,u=36*ce+22,l=ye[u];if(l)return ce=l.nextPos,l.result;if(e=ce,47===t.charCodeAt(ce)?(r="/",ce++):(r=s,ge($)),r!==s){if(n=[],(o=Ie())===s&&(o=je())===s&&(o=Te()),o!==s)for(;o!==s;)n.push(o),(o=Ie())===s&&(o=je())===s&&(o=Te());else n=s;n!==s?(47===t.charCodeAt(ce)?(o="/",ce++):(o=s,ge($)),o!==s?((a=function(){var e,r,n=36*ce+21,o=ye[n];if(o)return ce=o.nextPos,o.result;if(e=[],H.test(t.charAt(ce))?(r=t.charAt(ce),ce++):(r=s,ge(Y)),r!==s)for(;r!==s;)e.push(r),H.test(t.charAt(ce))?(r=t.charAt(ce),ce++):(r=s,ge(Y));else e=s;return ye[n]={nextPos:ce,result:e},e}())===s&&(a=null),a!==s?(i=a,r={type:"regexp",value:new RegExp(n.join(""),i?i.join(""):"")},e=r):(ce=e,e=s)):(ce=e,e=s)):(ce=e,e=s)}else ce=e,e=s;return ye[u]={nextPos:ce,result:e},e}()),o!==s?(r=I(r,n,o),e=r):(ce=e,e=s)):(ce=e,e=s),e===s&&(e=ce,(r=De())!==s&&Ee()!==s&&(n=function(){var e,r,n,o=36*ce+13,a=ye[o];return a?(ce=a.nextPos,a.result):(e=ce,S.test(t.charAt(ce))?(r=t.charAt(ce),ce++):(r=s,ge(_)),r===s&&(r=null),r!==s?(61===t.charCodeAt(ce)?(n="=",ce++):(n=s,ge(C)),n!==s?(r=P(r),e=r):(ce=e,e=s)):(ce=e,e=s),e===s&&(w.test(t.charAt(ce))?(e=t.charAt(ce),ce++):(e=s,ge(k))),ye[o]={nextPos:ce,result:e},e)}())!==s&&Ee()!==s?((o=function(){var e,r,n,o,a,i,u=36*ce+17,l=ye[u];if(l)return ce=l.nextPos,l.result;if(e=ce,34===t.charCodeAt(ce)?(r='"',ce++):(r=s,ge(j)),r!==s){for(n=[],T.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(F)),o===s&&(o=ce,92===t.charCodeAt(ce)?(a="\\",ce++):(a=s,ge(R)),a!==s?(t.length>ce?(i=t.charAt(ce),ce++):(i=s,ge(O)),i!==s?(a=L(a,i),o=a):(ce=o,o=s)):(ce=o,o=s));o!==s;)n.push(o),T.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(F)),o===s&&(o=ce,92===t.charCodeAt(ce)?(a="\\",ce++):(a=s,ge(R)),a!==s?(t.length>ce?(i=t.charAt(ce),ce++):(i=s,ge(O)),i!==s?(a=L(a,i),o=a):(ce=o,o=s)):(ce=o,o=s));n!==s?(34===t.charCodeAt(ce)?(o='"',ce++):(o=s,ge(j)),o!==s?(r=M(n),e=r):(ce=e,e=s)):(ce=e,e=s)}else ce=e,e=s;if(e===s)if(e=ce,39===t.charCodeAt(ce)?(r="'",ce++):(r=s,ge(B)),r!==s){for(n=[],U.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(K)),o===s&&(o=ce,92===t.charCodeAt(ce)?(a="\\",ce++):(a=s,ge(R)),a!==s?(t.length>ce?(i=t.charAt(ce),ce++):(i=s,ge(O)),i!==s?(a=L(a,i),o=a):(ce=o,o=s)):(ce=o,o=s));o!==s;)n.push(o),U.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(K)),o===s&&(o=ce,92===t.charCodeAt(ce)?(a="\\",ce++):(a=s,ge(R)),a!==s?(t.length>ce?(i=t.charAt(ce),ce++):(i=s,ge(O)),i!==s?(a=L(a,i),o=a):(ce=o,o=s)):(ce=o,o=s));n!==s?(39===t.charCodeAt(ce)?(o="'",ce++):(o=s,ge(B)),o!==s?(r=M(n),e=r):(ce=e,e=s)):(ce=e,e=s)}else ce=e,e=s;return ye[u]={nextPos:ce,result:e},e}())===s&&(o=function(){var e,r,n,o,a,i,u,l=36*ce+18,c=ye[l];if(c)return ce=c.nextPos,c.result;for(e=ce,r=ce,n=[],N.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(W));o!==s;)n.push(o),N.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(W));if(n!==s?(46===t.charCodeAt(ce)?(o=".",ce++):(o=s,ge(D)),o!==s?r=n=[n,o]:(ce=r,r=s)):(ce=r,r=s),r===s&&(r=null),r!==s){if(n=[],N.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(W)),o!==s)for(;o!==s;)n.push(o),N.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(W));else n=s;n!==s?(i=n,u=(a=r)?[].concat.apply([],a).join(""):"",r={type:"literal",value:parseFloat(u+i.join(""))},e=r):(ce=e,e=s)}else ce=e,e=s;return ye[l]={nextPos:ce,result:e},e}())===s&&(o=function(){var e,t,r=36*ce+19,n=ye[r];return n?(ce=n.nextPos,n.result):((t=be())!==s&&(t={type:"literal",value:t}),e=t,ye[r]={nextPos:ce,result:e},e)}()),o!==s?(r=I(r,n,o),e=r):(ce=e,e=s)):(ce=e,e=s),e===s&&(e=ce,(r=De())!==s&&(r={type:"attribute",name:r}),e=r)),ye[a]={nextPos:ce,result:e},e)}())!==s&&Ee()!==s?(93===t.charCodeAt(ce)?(o="]",ce++):(o=s,ge(b)),o!==s?e=r=n:(ce=e,e=s)):(ce=e,e=s),ye[a]={nextPos:ce,result:e},e)}())===s&&(e=function(){var e,r,n,o,a,i,u,l,c=36*ce+26,f=ye[c];if(f)return ce=f.nextPos,f.result;if(e=ce,46===t.charCodeAt(ce)?(r=".",ce++):(r=s,ge(D)),r!==s)if((n=be())!==s){for(o=[],a=ce,46===t.charCodeAt(ce)?(i=".",ce++):(i=s,ge(D)),i!==s&&(u=be())!==s?a=i=[i,u]:(ce=a,a=s);a!==s;)o.push(a),a=ce,46===t.charCodeAt(ce)?(i=".",ce++):(i=s,ge(D)),i!==s&&(u=be())!==s?a=i=[i,u]:(ce=a,a=s);o!==s?(l=n,r={type:"field",name:o.reduce((function(e,t){return e+t[0]+t[1]}),l)},e=r):(ce=e,e=s)}else ce=e,e=s;else ce=e,e=s;return ye[c]={nextPos:ce,result:e},e}())===s&&(e=function(){var e,r,n,o,a=36*ce+27,i=ye[a];return i?(ce=i.nextPos,i.result):(e=ce,":not("===t.substr(ce,5)?(r=":not(",ce+=5):(r=s,ge(ee)),r!==s&&Ee()!==s&&(n=_e())!==s&&Ee()!==s?(41===t.charCodeAt(ce)?(o=")",ce++):(o=s,ge(z)),o!==s?e=r={type:"not",selectors:n}:(ce=e,e=s)):(ce=e,e=s),ye[a]={nextPos:ce,result:e},e)}())===s&&(e=function(){var e,r,n,o,a=36*ce+28,i=ye[a];return i?(ce=i.nextPos,i.result):(e=ce,":matches("===t.substr(ce,9)?(r=":matches(",ce+=9):(r=s,ge(te)),r!==s&&Ee()!==s&&(n=_e())!==s&&Ee()!==s?(41===t.charCodeAt(ce)?(o=")",ce++):(o=s,ge(z)),o!==s?(r=re(n),e=r):(ce=e,e=s)):(ce=e,e=s),ye[a]={nextPos:ce,result:e},e)}())===s&&(e=function(){var e,r,n,o,a=36*ce+29,i=ye[a];return i?(ce=i.nextPos,i.result):(e=ce,":is("===t.substr(ce,4)?(r=":is(",ce+=4):(r=s,ge(ne)),r!==s&&Ee()!==s&&(n=_e())!==s&&Ee()!==s?(41===t.charCodeAt(ce)?(o=")",ce++):(o=s,ge(z)),o!==s?(r=re(n),e=r):(ce=e,e=s)):(ce=e,e=s),ye[a]={nextPos:ce,result:e},e)}())===s&&(e=function(){var e,r,n,o,a=36*ce+30,i=ye[a];return i?(ce=i.nextPos,i.result):(e=ce,":has("===t.substr(ce,5)?(r=":has(",ce+=5):(r=s,ge(oe)),r!==s&&Ee()!==s&&(n=function(){var e,r,n,o,a,i,u,l,c=36*ce+4,f=ye[c];if(f)return ce=f.nextPos,f.result;if(e=ce,(r=Ce())!==s){for(n=[],o=ce,(a=Ee())!==s?(44===t.charCodeAt(ce)?(i=",",ce++):(i=s,ge(m)),i!==s&&(u=Ee())!==s&&(l=Ce())!==s?o=a=[a,i,u,l]:(ce=o,o=s)):(ce=o,o=s);o!==s;)n.push(o),o=ce,(a=Ee())!==s?(44===t.charCodeAt(ce)?(i=",",ce++):(i=s,ge(m)),i!==s&&(u=Ee())!==s&&(l=Ce())!==s?o=a=[a,i,u,l]:(ce=o,o=s)):(ce=o,o=s);n!==s?e=r=x(r,n):(ce=e,e=s)}else ce=e,e=s;return ye[c]={nextPos:ce,result:e},e}())!==s&&Ee()!==s?(41===t.charCodeAt(ce)?(o=")",ce++):(o=s,ge(z)),o!==s?e=r={type:"has",selectors:n}:(ce=e,e=s)):(ce=e,e=s),ye[a]={nextPos:ce,result:e},e)}())===s&&(e=function(){var e,r,n=36*ce+31,o=ye[n];return o?(ce=o.nextPos,o.result):(":first-child"===t.substr(ce,12)?(r=":first-child",ce+=12):(r=s,ge(ae)),r!==s&&(r=Fe(1)),e=r,ye[n]={nextPos:ce,result:e},e)}())===s&&(e=function(){var e,r,n=36*ce+32,o=ye[n];return o?(ce=o.nextPos,o.result):(":last-child"===t.substr(ce,11)?(r=":last-child",ce+=11):(r=s,ge(ie)),r!==s&&(r=Re(1)),e=r,ye[n]={nextPos:ce,result:e},e)}())===s&&(e=function(){var e,r,n,o,a,i=36*ce+33,u=ye[i];if(u)return ce=u.nextPos,u.result;if(e=ce,":nth-child("===t.substr(ce,11)?(r=":nth-child(",ce+=11):(r=s,ge(se)),r!==s)if(Ee()!==s){if(n=[],N.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(W)),o!==s)for(;o!==s;)n.push(o),N.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(W));else n=s;n!==s&&(o=Ee())!==s?(41===t.charCodeAt(ce)?(a=")",ce++):(a=s,ge(z)),a!==s?(r=Fe(parseInt(n.join(""),10)),e=r):(ce=e,e=s)):(ce=e,e=s)}else ce=e,e=s;else ce=e,e=s;return ye[i]={nextPos:ce,result:e},e}())===s&&(e=function(){var e,r,n,o,a,i=36*ce+34,u=ye[i];if(u)return ce=u.nextPos,u.result;if(e=ce,":nth-last-child("===t.substr(ce,16)?(r=":nth-last-child(",ce+=16):(r=s,ge(ue)),r!==s)if(Ee()!==s){if(n=[],N.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(W)),o!==s)for(;o!==s;)n.push(o),N.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(W));else n=s;n!==s&&(o=Ee())!==s?(41===t.charCodeAt(ce)?(a=")",ce++):(a=s,ge(z)),a!==s?(r=Re(parseInt(n.join(""),10)),e=r):(ce=e,e=s)):(ce=e,e=s)}else ce=e,e=s;else ce=e,e=s;return ye[i]={nextPos:ce,result:e},e}())===s&&(e=function(){var e,r,n,o=36*ce+35,a=ye[o];return a?(ce=a.nextPos,a.result):(e=ce,58===t.charCodeAt(ce)?(r=":",ce++):(r=s,ge(le)),r!==s&&(n=be())!==s?e=r={type:"class",name:n}:(ce=e,e=s),ye[o]={nextPos:ce,result:e},e)}()),ye[r]={nextPos:ce,result:e},e)}function De(){var e,r,n,o,a,i,u,l,c=36*ce+15,f=ye[c];if(f)return ce=f.nextPos,f.result;if(e=ce,(r=be())!==s){for(n=[],o=ce,46===t.charCodeAt(ce)?(a=".",ce++):(a=s,ge(D)),a!==s&&(i=be())!==s?o=a=[a,i]:(ce=o,o=s);o!==s;)n.push(o),o=ce,46===t.charCodeAt(ce)?(a=".",ce++):(a=s,ge(D)),a!==s&&(i=be())!==s?o=a=[a,i]:(ce=o,o=s);n!==s?(u=r,l=n,e=r=[].concat.apply([u],l).join("")):(ce=e,e=s)}else ce=e,e=s;return ye[c]={nextPos:ce,result:e},e}function Ie(){var e,r,n,o,a=36*ce+23,i=ye[a];if(i)return ce=i.nextPos,i.result;if(e=ce,91===t.charCodeAt(ce)?(r="[",ce++):(r=s,ge(E)),r!==s){if(n=[],J.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(Q)),o===s&&(o=je()),o!==s)for(;o!==s;)n.push(o),J.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(Q)),o===s&&(o=je());else n=s;n!==s?(93===t.charCodeAt(ce)?(o="]",ce++):(o=s,ge(b)),o!==s?e=r="["+n.join("")+"]":(ce=e,e=s)):(ce=e,e=s)}else ce=e,e=s;return ye[a]={nextPos:ce,result:e},e}function je(){var e,r,n,o=36*ce+24,a=ye[o];return a?(ce=a.nextPos,a.result):(e=ce,92===t.charCodeAt(ce)?(r="\\",ce++):(r=s,ge(R)),r!==s?(t.length>ce?(n=t.charAt(ce),ce++):(n=s,ge(O)),n!==s?e=r="\\"+n:(ce=e,e=s)):(ce=e,e=s),ye[o]={nextPos:ce,result:e},e)}function Te(){var e,r,n,o=36*ce+25,a=ye[o];if(a)return ce=a.nextPos,a.result;if(r=[],X.test(t.charAt(ce))?(n=t.charAt(ce),ce++):(n=s,ge(Z)),n!==s)for(;n!==s;)r.push(n),X.test(t.charAt(ce))?(n=t.charAt(ce),ce++):(n=s,ge(Z));else r=s;return r!==s&&(r=r.join("")),e=r,ye[o]={nextPos:ce,result:e},e}function Fe(e){return{type:"nth-child",index:{type:"literal",value:e}}}function Re(e){return{type:"nth-last-child",index:{type:"literal",value:e}}}if((n=l())!==s&&ce===t.length)return n;throw n!==s&&ce0&&p(e,t,r))&&f(t[0],t.slice(1),r)};case"descendant":var h=c(e.left),x=c(e.right);return function(e,t,r){if(x(e,t,r))for(var n=0,o=t.length;n":return function(t){return u(t,v)>e.value.value};case">=":return function(t){return u(t,v)>=e.value.value}}throw new Error("Unknown operator: ".concat(e.operator));case"sibling":var E=c(e.left),b=c(e.right);return function(t,r,n){return b(t,r,n)&&y(t,E,r,"LEFT_SIDE",n)||e.left.subject&&E(t,r,n)&&y(t,b,r,"RIGHT_SIDE",n)};case"adjacent":var S=c(e.left),_=c(e.right);return function(t,r,n){return _(t,r,n)&&d(t,S,r,"LEFT_SIDE",n)||e.right.subject&&S(t,r,n)&&d(t,_,r,"RIGHT_SIDE",n)};case"nth-child":var C=e.index.value,P=c(e.right);return function(e,t,r){return P(e,t,r)&&m(e,t,C,r)};case"nth-last-child":var w=-e.index.value,k=c(e.right);return function(e,t,r){return k(e,t,r)&&m(e,t,w,r)};case"class":var D=e.name.toLowerCase();return function(t,r,n){if(n&&n.matchClass)return n.matchClass(e.name,t,r);if(n&&n.nodeTypeKey)return!1;switch(D){case"statement":if("Statement"===t.type.slice(-9))return!0;case"declaration":return"Declaration"===t.type.slice(-11);case"pattern":if("Pattern"===t.type.slice(-7))return!0;case"expression":return"Expression"===t.type.slice(-10)||"Literal"===t.type.slice(-7)||"Identifier"===t.type&&(0===r.length||"MetaProperty"!==r[0].type)||"MetaProperty"===t.type;case"function":return"FunctionDeclaration"===t.type||"FunctionExpression"===t.type||"ArrowFunctionExpression"===t.type}throw new Error("Unknown class name: ".concat(e.name))}}throw new Error("Unknown selector type: ".concat(e.type))}function p(e,t){var r=t&&t.nodeTypeKey||"type",n=e[r];return t&&t.visitorKeys&&t.visitorKeys[n]?t.visitorKeys[n]:i.VisitorKeys[n]?i.VisitorKeys[n]:t&&"function"==typeof t.fallback?t.fallback(e):Object.keys(e).filter((function(e){return e!==r}))}function h(e,t){var r=t&&t.nodeTypeKey||"type";return null!==e&&"object"===n(e)&&"string"==typeof e[r]}function y(e,r,n,o,a){var i=t(n,1)[0];if(!i)return!1;for(var s=p(i,a),u=0;u0&&h(l[c-1],a)&&r(l[c-1],n,a))return!0;if("RIGHT_SIDE"===o&&c=0&&l\n Copyright (C) 2012 Ariya Hidayat \n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/*jslint vars:false, bitwise:true*/\n/*jshint indent:4*/\n/*global exports:true*/\n(function clone(exports) {\n 'use strict';\n\n var Syntax,\n VisitorOption,\n VisitorKeys,\n BREAK,\n SKIP,\n REMOVE;\n\n function deepCopy(obj) {\n var ret = {}, key, val;\n for (key in obj) {\n if (obj.hasOwnProperty(key)) {\n val = obj[key];\n if (typeof val === 'object' && val !== null) {\n ret[key] = deepCopy(val);\n } else {\n ret[key] = val;\n }\n }\n }\n return ret;\n }\n\n // based on LLVM libc++ upper_bound / lower_bound\n // MIT License\n\n function upperBound(array, func) {\n var diff, len, i, current;\n\n len = array.length;\n i = 0;\n\n while (len) {\n diff = len >>> 1;\n current = i + diff;\n if (func(array[current])) {\n len = diff;\n } else {\n i = current + 1;\n len -= diff + 1;\n }\n }\n return i;\n }\n\n Syntax = {\n AssignmentExpression: 'AssignmentExpression',\n AssignmentPattern: 'AssignmentPattern',\n ArrayExpression: 'ArrayExpression',\n ArrayPattern: 'ArrayPattern',\n ArrowFunctionExpression: 'ArrowFunctionExpression',\n AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7.\n BlockStatement: 'BlockStatement',\n BinaryExpression: 'BinaryExpression',\n BreakStatement: 'BreakStatement',\n CallExpression: 'CallExpression',\n CatchClause: 'CatchClause',\n ChainExpression: 'ChainExpression',\n ClassBody: 'ClassBody',\n ClassDeclaration: 'ClassDeclaration',\n ClassExpression: 'ClassExpression',\n ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7.\n ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7.\n ConditionalExpression: 'ConditionalExpression',\n ContinueStatement: 'ContinueStatement',\n DebuggerStatement: 'DebuggerStatement',\n DirectiveStatement: 'DirectiveStatement',\n DoWhileStatement: 'DoWhileStatement',\n EmptyStatement: 'EmptyStatement',\n ExportAllDeclaration: 'ExportAllDeclaration',\n ExportDefaultDeclaration: 'ExportDefaultDeclaration',\n ExportNamedDeclaration: 'ExportNamedDeclaration',\n ExportSpecifier: 'ExportSpecifier',\n ExpressionStatement: 'ExpressionStatement',\n ForStatement: 'ForStatement',\n ForInStatement: 'ForInStatement',\n ForOfStatement: 'ForOfStatement',\n FunctionDeclaration: 'FunctionDeclaration',\n FunctionExpression: 'FunctionExpression',\n GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7.\n Identifier: 'Identifier',\n IfStatement: 'IfStatement',\n ImportExpression: 'ImportExpression',\n ImportDeclaration: 'ImportDeclaration',\n ImportDefaultSpecifier: 'ImportDefaultSpecifier',\n ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',\n ImportSpecifier: 'ImportSpecifier',\n Literal: 'Literal',\n LabeledStatement: 'LabeledStatement',\n LogicalExpression: 'LogicalExpression',\n MemberExpression: 'MemberExpression',\n MetaProperty: 'MetaProperty',\n MethodDefinition: 'MethodDefinition',\n ModuleSpecifier: 'ModuleSpecifier',\n NewExpression: 'NewExpression',\n ObjectExpression: 'ObjectExpression',\n ObjectPattern: 'ObjectPattern',\n PrivateIdentifier: 'PrivateIdentifier',\n Program: 'Program',\n Property: 'Property',\n PropertyDefinition: 'PropertyDefinition',\n RestElement: 'RestElement',\n ReturnStatement: 'ReturnStatement',\n SequenceExpression: 'SequenceExpression',\n SpreadElement: 'SpreadElement',\n Super: 'Super',\n SwitchStatement: 'SwitchStatement',\n SwitchCase: 'SwitchCase',\n TaggedTemplateExpression: 'TaggedTemplateExpression',\n TemplateElement: 'TemplateElement',\n TemplateLiteral: 'TemplateLiteral',\n ThisExpression: 'ThisExpression',\n ThrowStatement: 'ThrowStatement',\n TryStatement: 'TryStatement',\n UnaryExpression: 'UnaryExpression',\n UpdateExpression: 'UpdateExpression',\n VariableDeclaration: 'VariableDeclaration',\n VariableDeclarator: 'VariableDeclarator',\n WhileStatement: 'WhileStatement',\n WithStatement: 'WithStatement',\n YieldExpression: 'YieldExpression'\n };\n\n VisitorKeys = {\n AssignmentExpression: ['left', 'right'],\n AssignmentPattern: ['left', 'right'],\n ArrayExpression: ['elements'],\n ArrayPattern: ['elements'],\n ArrowFunctionExpression: ['params', 'body'],\n AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7.\n BlockStatement: ['body'],\n BinaryExpression: ['left', 'right'],\n BreakStatement: ['label'],\n CallExpression: ['callee', 'arguments'],\n CatchClause: ['param', 'body'],\n ChainExpression: ['expression'],\n ClassBody: ['body'],\n ClassDeclaration: ['id', 'superClass', 'body'],\n ClassExpression: ['id', 'superClass', 'body'],\n ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7.\n ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.\n ConditionalExpression: ['test', 'consequent', 'alternate'],\n ContinueStatement: ['label'],\n DebuggerStatement: [],\n DirectiveStatement: [],\n DoWhileStatement: ['body', 'test'],\n EmptyStatement: [],\n ExportAllDeclaration: ['source'],\n ExportDefaultDeclaration: ['declaration'],\n ExportNamedDeclaration: ['declaration', 'specifiers', 'source'],\n ExportSpecifier: ['exported', 'local'],\n ExpressionStatement: ['expression'],\n ForStatement: ['init', 'test', 'update', 'body'],\n ForInStatement: ['left', 'right', 'body'],\n ForOfStatement: ['left', 'right', 'body'],\n FunctionDeclaration: ['id', 'params', 'body'],\n FunctionExpression: ['id', 'params', 'body'],\n GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.\n Identifier: [],\n IfStatement: ['test', 'consequent', 'alternate'],\n ImportExpression: ['source'],\n ImportDeclaration: ['specifiers', 'source'],\n ImportDefaultSpecifier: ['local'],\n ImportNamespaceSpecifier: ['local'],\n ImportSpecifier: ['imported', 'local'],\n Literal: [],\n LabeledStatement: ['label', 'body'],\n LogicalExpression: ['left', 'right'],\n MemberExpression: ['object', 'property'],\n MetaProperty: ['meta', 'property'],\n MethodDefinition: ['key', 'value'],\n ModuleSpecifier: [],\n NewExpression: ['callee', 'arguments'],\n ObjectExpression: ['properties'],\n ObjectPattern: ['properties'],\n PrivateIdentifier: [],\n Program: ['body'],\n Property: ['key', 'value'],\n PropertyDefinition: ['key', 'value'],\n RestElement: [ 'argument' ],\n ReturnStatement: ['argument'],\n SequenceExpression: ['expressions'],\n SpreadElement: ['argument'],\n Super: [],\n SwitchStatement: ['discriminant', 'cases'],\n SwitchCase: ['test', 'consequent'],\n TaggedTemplateExpression: ['tag', 'quasi'],\n TemplateElement: [],\n TemplateLiteral: ['quasis', 'expressions'],\n ThisExpression: [],\n ThrowStatement: ['argument'],\n TryStatement: ['block', 'handler', 'finalizer'],\n UnaryExpression: ['argument'],\n UpdateExpression: ['argument'],\n VariableDeclaration: ['declarations'],\n VariableDeclarator: ['id', 'init'],\n WhileStatement: ['test', 'body'],\n WithStatement: ['object', 'body'],\n YieldExpression: ['argument']\n };\n\n // unique id\n BREAK = {};\n SKIP = {};\n REMOVE = {};\n\n VisitorOption = {\n Break: BREAK,\n Skip: SKIP,\n Remove: REMOVE\n };\n\n function Reference(parent, key) {\n this.parent = parent;\n this.key = key;\n }\n\n Reference.prototype.replace = function replace(node) {\n this.parent[this.key] = node;\n };\n\n Reference.prototype.remove = function remove() {\n if (Array.isArray(this.parent)) {\n this.parent.splice(this.key, 1);\n return true;\n } else {\n this.replace(null);\n return false;\n }\n };\n\n function Element(node, path, wrap, ref) {\n this.node = node;\n this.path = path;\n this.wrap = wrap;\n this.ref = ref;\n }\n\n function Controller() { }\n\n // API:\n // return property path array from root to current node\n Controller.prototype.path = function path() {\n var i, iz, j, jz, result, element;\n\n function addToPath(result, path) {\n if (Array.isArray(path)) {\n for (j = 0, jz = path.length; j < jz; ++j) {\n result.push(path[j]);\n }\n } else {\n result.push(path);\n }\n }\n\n // root node\n if (!this.__current.path) {\n return null;\n }\n\n // first node is sentinel, second node is root element\n result = [];\n for (i = 2, iz = this.__leavelist.length; i < iz; ++i) {\n element = this.__leavelist[i];\n addToPath(result, element.path);\n }\n addToPath(result, this.__current.path);\n return result;\n };\n\n // API:\n // return type of current node\n Controller.prototype.type = function () {\n var node = this.current();\n return node.type || this.__current.wrap;\n };\n\n // API:\n // return array of parent elements\n Controller.prototype.parents = function parents() {\n var i, iz, result;\n\n // first node is sentinel\n result = [];\n for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {\n result.push(this.__leavelist[i].node);\n }\n\n return result;\n };\n\n // API:\n // return current node\n Controller.prototype.current = function current() {\n return this.__current.node;\n };\n\n Controller.prototype.__execute = function __execute(callback, element) {\n var previous, result;\n\n result = undefined;\n\n previous = this.__current;\n this.__current = element;\n this.__state = null;\n if (callback) {\n result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node);\n }\n this.__current = previous;\n\n return result;\n };\n\n // API:\n // notify control skip / break\n Controller.prototype.notify = function notify(flag) {\n this.__state = flag;\n };\n\n // API:\n // skip child nodes of current node\n Controller.prototype.skip = function () {\n this.notify(SKIP);\n };\n\n // API:\n // break traversals\n Controller.prototype['break'] = function () {\n this.notify(BREAK);\n };\n\n // API:\n // remove node\n Controller.prototype.remove = function () {\n this.notify(REMOVE);\n };\n\n Controller.prototype.__initialize = function(root, visitor) {\n this.visitor = visitor;\n this.root = root;\n this.__worklist = [];\n this.__leavelist = [];\n this.__current = null;\n this.__state = null;\n this.__fallback = null;\n if (visitor.fallback === 'iteration') {\n this.__fallback = Object.keys;\n } else if (typeof visitor.fallback === 'function') {\n this.__fallback = visitor.fallback;\n }\n\n this.__keys = VisitorKeys;\n if (visitor.keys) {\n this.__keys = Object.assign(Object.create(this.__keys), visitor.keys);\n }\n };\n\n function isNode(node) {\n if (node == null) {\n return false;\n }\n return typeof node === 'object' && typeof node.type === 'string';\n }\n\n function isProperty(nodeType, key) {\n return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key;\n }\n \n function candidateExistsInLeaveList(leavelist, candidate) {\n for (var i = leavelist.length - 1; i >= 0; --i) {\n if (leavelist[i].node === candidate) {\n return true;\n }\n }\n return false;\n }\n\n Controller.prototype.traverse = function traverse(root, visitor) {\n var worklist,\n leavelist,\n element,\n node,\n nodeType,\n ret,\n key,\n current,\n current2,\n candidates,\n candidate,\n sentinel;\n\n this.__initialize(root, visitor);\n\n sentinel = {};\n\n // reference\n worklist = this.__worklist;\n leavelist = this.__leavelist;\n\n // initialize\n worklist.push(new Element(root, null, null, null));\n leavelist.push(new Element(null, null, null, null));\n\n while (worklist.length) {\n element = worklist.pop();\n\n if (element === sentinel) {\n element = leavelist.pop();\n\n ret = this.__execute(visitor.leave, element);\n\n if (this.__state === BREAK || ret === BREAK) {\n return;\n }\n continue;\n }\n\n if (element.node) {\n\n ret = this.__execute(visitor.enter, element);\n\n if (this.__state === BREAK || ret === BREAK) {\n return;\n }\n\n worklist.push(sentinel);\n leavelist.push(element);\n\n if (this.__state === SKIP || ret === SKIP) {\n continue;\n }\n\n node = element.node;\n nodeType = node.type || element.wrap;\n candidates = this.__keys[nodeType];\n if (!candidates) {\n if (this.__fallback) {\n candidates = this.__fallback(node);\n } else {\n throw new Error('Unknown node type ' + nodeType + '.');\n }\n }\n\n current = candidates.length;\n while ((current -= 1) >= 0) {\n key = candidates[current];\n candidate = node[key];\n if (!candidate) {\n continue;\n }\n\n if (Array.isArray(candidate)) {\n current2 = candidate.length;\n while ((current2 -= 1) >= 0) {\n if (!candidate[current2]) {\n continue;\n }\n\n if (candidateExistsInLeaveList(leavelist, candidate[current2])) {\n continue;\n }\n\n if (isProperty(nodeType, candidates[current])) {\n element = new Element(candidate[current2], [key, current2], 'Property', null);\n } else if (isNode(candidate[current2])) {\n element = new Element(candidate[current2], [key, current2], null, null);\n } else {\n continue;\n }\n worklist.push(element);\n }\n } else if (isNode(candidate)) {\n if (candidateExistsInLeaveList(leavelist, candidate)) {\n continue;\n }\n\n worklist.push(new Element(candidate, key, null, null));\n }\n }\n }\n }\n };\n\n Controller.prototype.replace = function replace(root, visitor) {\n var worklist,\n leavelist,\n node,\n nodeType,\n target,\n element,\n current,\n current2,\n candidates,\n candidate,\n sentinel,\n outer,\n key;\n\n function removeElem(element) {\n var i,\n key,\n nextElem,\n parent;\n\n if (element.ref.remove()) {\n // When the reference is an element of an array.\n key = element.ref.key;\n parent = element.ref.parent;\n\n // If removed from array, then decrease following items' keys.\n i = worklist.length;\n while (i--) {\n nextElem = worklist[i];\n if (nextElem.ref && nextElem.ref.parent === parent) {\n if (nextElem.ref.key < key) {\n break;\n }\n --nextElem.ref.key;\n }\n }\n }\n }\n\n this.__initialize(root, visitor);\n\n sentinel = {};\n\n // reference\n worklist = this.__worklist;\n leavelist = this.__leavelist;\n\n // initialize\n outer = {\n root: root\n };\n element = new Element(root, null, null, new Reference(outer, 'root'));\n worklist.push(element);\n leavelist.push(element);\n\n while (worklist.length) {\n element = worklist.pop();\n\n if (element === sentinel) {\n element = leavelist.pop();\n\n target = this.__execute(visitor.leave, element);\n\n // node may be replaced with null,\n // so distinguish between undefined and null in this place\n if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {\n // replace\n element.ref.replace(target);\n }\n\n if (this.__state === REMOVE || target === REMOVE) {\n removeElem(element);\n }\n\n if (this.__state === BREAK || target === BREAK) {\n return outer.root;\n }\n continue;\n }\n\n target = this.__execute(visitor.enter, element);\n\n // node may be replaced with null,\n // so distinguish between undefined and null in this place\n if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {\n // replace\n element.ref.replace(target);\n element.node = target;\n }\n\n if (this.__state === REMOVE || target === REMOVE) {\n removeElem(element);\n element.node = null;\n }\n\n if (this.__state === BREAK || target === BREAK) {\n return outer.root;\n }\n\n // node may be null\n node = element.node;\n if (!node) {\n continue;\n }\n\n worklist.push(sentinel);\n leavelist.push(element);\n\n if (this.__state === SKIP || target === SKIP) {\n continue;\n }\n\n nodeType = node.type || element.wrap;\n candidates = this.__keys[nodeType];\n if (!candidates) {\n if (this.__fallback) {\n candidates = this.__fallback(node);\n } else {\n throw new Error('Unknown node type ' + nodeType + '.');\n }\n }\n\n current = candidates.length;\n while ((current -= 1) >= 0) {\n key = candidates[current];\n candidate = node[key];\n if (!candidate) {\n continue;\n }\n\n if (Array.isArray(candidate)) {\n current2 = candidate.length;\n while ((current2 -= 1) >= 0) {\n if (!candidate[current2]) {\n continue;\n }\n if (isProperty(nodeType, candidates[current])) {\n element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2));\n } else if (isNode(candidate[current2])) {\n element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2));\n } else {\n continue;\n }\n worklist.push(element);\n }\n } else if (isNode(candidate)) {\n worklist.push(new Element(candidate, key, null, new Reference(node, key)));\n }\n }\n }\n\n return outer.root;\n };\n\n function traverse(root, visitor) {\n var controller = new Controller();\n return controller.traverse(root, visitor);\n }\n\n function replace(root, visitor) {\n var controller = new Controller();\n return controller.replace(root, visitor);\n }\n\n function extendCommentRange(comment, tokens) {\n var target;\n\n target = upperBound(tokens, function search(token) {\n return token.range[0] > comment.range[0];\n });\n\n comment.extendedRange = [comment.range[0], comment.range[1]];\n\n if (target !== tokens.length) {\n comment.extendedRange[1] = tokens[target].range[0];\n }\n\n target -= 1;\n if (target >= 0) {\n comment.extendedRange[0] = tokens[target].range[1];\n }\n\n return comment;\n }\n\n function attachComments(tree, providedComments, tokens) {\n // At first, we should calculate extended comment ranges.\n var comments = [], comment, len, i, cursor;\n\n if (!tree.range) {\n throw new Error('attachComments needs range information');\n }\n\n // tokens array is empty, we attach comments to tree as 'leadingComments'\n if (!tokens.length) {\n if (providedComments.length) {\n for (i = 0, len = providedComments.length; i < len; i += 1) {\n comment = deepCopy(providedComments[i]);\n comment.extendedRange = [0, tree.range[0]];\n comments.push(comment);\n }\n tree.leadingComments = comments;\n }\n return tree;\n }\n\n for (i = 0, len = providedComments.length; i < len; i += 1) {\n comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens));\n }\n\n // This is based on John Freeman's implementation.\n cursor = 0;\n traverse(tree, {\n enter: function (node) {\n var comment;\n\n while (cursor < comments.length) {\n comment = comments[cursor];\n if (comment.extendedRange[1] > node.range[0]) {\n break;\n }\n\n if (comment.extendedRange[1] === node.range[0]) {\n if (!node.leadingComments) {\n node.leadingComments = [];\n }\n node.leadingComments.push(comment);\n comments.splice(cursor, 1);\n } else {\n cursor += 1;\n }\n }\n\n // already out of owned node\n if (cursor === comments.length) {\n return VisitorOption.Break;\n }\n\n if (comments[cursor].extendedRange[0] > node.range[1]) {\n return VisitorOption.Skip;\n }\n }\n });\n\n cursor = 0;\n traverse(tree, {\n leave: function (node) {\n var comment;\n\n while (cursor < comments.length) {\n comment = comments[cursor];\n if (node.range[1] < comment.extendedRange[0]) {\n break;\n }\n\n if (node.range[1] === comment.extendedRange[0]) {\n if (!node.trailingComments) {\n node.trailingComments = [];\n }\n node.trailingComments.push(comment);\n comments.splice(cursor, 1);\n } else {\n cursor += 1;\n }\n }\n\n // already out of owned node\n if (cursor === comments.length) {\n return VisitorOption.Break;\n }\n\n if (comments[cursor].extendedRange[0] > node.range[1]) {\n return VisitorOption.Skip;\n }\n }\n });\n\n return tree;\n }\n\n exports.Syntax = Syntax;\n exports.traverse = traverse;\n exports.replace = replace;\n exports.attachComments = attachComments;\n exports.VisitorKeys = VisitorKeys;\n exports.VisitorOption = VisitorOption;\n exports.Controller = Controller;\n exports.cloneEnvironment = function () { return clone({}); };\n\n return exports;\n}(exports));\n/* vim: set sw=4 ts=4 et tw=80 : */\n","/*\n * Generated by PEG.js 0.10.0.\n *\n * http://pegjs.org/\n */\n(function(root, factory) {\n if (typeof define === \"function\" && define.amd) {\n define([], factory);\n } else if (typeof module === \"object\" && module.exports) {\n module.exports = factory();\n }\n})(this, function() {\n \"use strict\";\n\n function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }\n\n function peg$SyntaxError(message, expected, found, location) {\n this.message = message;\n this.expected = expected;\n this.found = found;\n this.location = location;\n this.name = \"SyntaxError\";\n\n if (typeof Error.captureStackTrace === \"function\") {\n Error.captureStackTrace(this, peg$SyntaxError);\n }\n }\n\n peg$subclass(peg$SyntaxError, Error);\n\n peg$SyntaxError.buildMessage = function(expected, found) {\n var DESCRIBE_EXPECTATION_FNS = {\n literal: function(expectation) {\n return \"\\\"\" + literalEscape(expectation.text) + \"\\\"\";\n },\n\n \"class\": function(expectation) {\n var escapedParts = \"\",\n i;\n\n for (i = 0; i < expectation.parts.length; i++) {\n escapedParts += expectation.parts[i] instanceof Array\n ? classEscape(expectation.parts[i][0]) + \"-\" + classEscape(expectation.parts[i][1])\n : classEscape(expectation.parts[i]);\n }\n\n return \"[\" + (expectation.inverted ? \"^\" : \"\") + escapedParts + \"]\";\n },\n\n any: function(expectation) {\n return \"any character\";\n },\n\n end: function(expectation) {\n return \"end of input\";\n },\n\n other: function(expectation) {\n return expectation.description;\n }\n };\n\n function hex(ch) {\n return ch.charCodeAt(0).toString(16).toUpperCase();\n }\n\n function literalEscape(s) {\n return s\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/\\0/g, '\\\\0')\n .replace(/\\t/g, '\\\\t')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/[\\x00-\\x0F]/g, function(ch) { return '\\\\x0' + hex(ch); })\n .replace(/[\\x10-\\x1F\\x7F-\\x9F]/g, function(ch) { return '\\\\x' + hex(ch); });\n }\n\n function classEscape(s) {\n return s\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\\]/g, '\\\\]')\n .replace(/\\^/g, '\\\\^')\n .replace(/-/g, '\\\\-')\n .replace(/\\0/g, '\\\\0')\n .replace(/\\t/g, '\\\\t')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/[\\x00-\\x0F]/g, function(ch) { return '\\\\x0' + hex(ch); })\n .replace(/[\\x10-\\x1F\\x7F-\\x9F]/g, function(ch) { return '\\\\x' + hex(ch); });\n }\n\n function describeExpectation(expectation) {\n return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation);\n }\n\n function describeExpected(expected) {\n var descriptions = new Array(expected.length),\n i, j;\n\n for (i = 0; i < expected.length; i++) {\n descriptions[i] = describeExpectation(expected[i]);\n }\n\n descriptions.sort();\n\n if (descriptions.length > 0) {\n for (i = 1, j = 1; i < descriptions.length; i++) {\n if (descriptions[i - 1] !== descriptions[i]) {\n descriptions[j] = descriptions[i];\n j++;\n }\n }\n descriptions.length = j;\n }\n\n switch (descriptions.length) {\n case 1:\n return descriptions[0];\n\n case 2:\n return descriptions[0] + \" or \" + descriptions[1];\n\n default:\n return descriptions.slice(0, -1).join(\", \")\n + \", or \"\n + descriptions[descriptions.length - 1];\n }\n }\n\n function describeFound(found) {\n return found ? \"\\\"\" + literalEscape(found) + \"\\\"\" : \"end of input\";\n }\n\n return \"Expected \" + describeExpected(expected) + \" but \" + describeFound(found) + \" found.\";\n };\n\n function peg$parse(input, options) {\n options = options !== void 0 ? options : {};\n\n var peg$FAILED = {},\n\n peg$startRuleFunctions = { start: peg$parsestart },\n peg$startRuleFunction = peg$parsestart,\n\n peg$c0 = function(ss) {\n return ss.length === 1 ? ss[0] : { type: 'matches', selectors: ss };\n },\n peg$c1 = function() { return void 0; },\n peg$c2 = \" \",\n peg$c3 = peg$literalExpectation(\" \", false),\n peg$c4 = /^[^ [\\],():#!=><~+.]/,\n peg$c5 = peg$classExpectation([\" \", \"[\", \"]\", \",\", \"(\", \")\", \":\", \"#\", \"!\", \"=\", \">\", \"<\", \"~\", \"+\", \".\"], true, false),\n peg$c6 = function(i) { return i.join(''); },\n peg$c7 = \">\",\n peg$c8 = peg$literalExpectation(\">\", false),\n peg$c9 = function() { return 'child'; },\n peg$c10 = \"~\",\n peg$c11 = peg$literalExpectation(\"~\", false),\n peg$c12 = function() { return 'sibling'; },\n peg$c13 = \"+\",\n peg$c14 = peg$literalExpectation(\"+\", false),\n peg$c15 = function() { return 'adjacent'; },\n peg$c16 = function() { return 'descendant'; },\n peg$c17 = \",\",\n peg$c18 = peg$literalExpectation(\",\", false),\n peg$c19 = function(s, ss) {\n return [s].concat(ss.map(function (s) { return s[3]; }));\n },\n peg$c20 = function(op, s) {\n if (!op) return s;\n return { type: op, left: { type: 'exactNode' }, right: s };\n },\n peg$c21 = function(a, ops) {\n return ops.reduce(function (memo, rhs) {\n return { type: rhs[0], left: memo, right: rhs[1] };\n }, a);\n },\n peg$c22 = \"!\",\n peg$c23 = peg$literalExpectation(\"!\", false),\n peg$c24 = function(subject, as) {\n const b = as.length === 1 ? as[0] : { type: 'compound', selectors: as };\n if(subject) b.subject = true;\n return b;\n },\n peg$c25 = \"*\",\n peg$c26 = peg$literalExpectation(\"*\", false),\n peg$c27 = function(a) { return { type: 'wildcard', value: a }; },\n peg$c28 = \"#\",\n peg$c29 = peg$literalExpectation(\"#\", false),\n peg$c30 = function(i) { return { type: 'identifier', value: i }; },\n peg$c31 = \"[\",\n peg$c32 = peg$literalExpectation(\"[\", false),\n peg$c33 = \"]\",\n peg$c34 = peg$literalExpectation(\"]\", false),\n peg$c35 = function(v) { return v; },\n peg$c36 = /^[>\", \"<\", \"!\"], false, false),\n peg$c38 = \"=\",\n peg$c39 = peg$literalExpectation(\"=\", false),\n peg$c40 = function(a) { return (a || '') + '='; },\n peg$c41 = /^[><]/,\n peg$c42 = peg$classExpectation([\">\", \"<\"], false, false),\n peg$c43 = \".\",\n peg$c44 = peg$literalExpectation(\".\", false),\n peg$c45 = function(a, as) {\n return [].concat.apply([a], as).join('');\n },\n peg$c46 = function(name, op, value) {\n return { type: 'attribute', name: name, operator: op, value: value };\n },\n peg$c47 = function(name) { return { type: 'attribute', name: name }; },\n peg$c48 = \"\\\"\",\n peg$c49 = peg$literalExpectation(\"\\\"\", false),\n peg$c50 = /^[^\\\\\"]/,\n peg$c51 = peg$classExpectation([\"\\\\\", \"\\\"\"], true, false),\n peg$c52 = \"\\\\\",\n peg$c53 = peg$literalExpectation(\"\\\\\", false),\n peg$c54 = peg$anyExpectation(),\n peg$c55 = function(a, b) { return a + b; },\n peg$c56 = function(d) {\n return { type: 'literal', value: strUnescape(d.join('')) };\n },\n peg$c57 = \"'\",\n peg$c58 = peg$literalExpectation(\"'\", false),\n peg$c59 = /^[^\\\\']/,\n peg$c60 = peg$classExpectation([\"\\\\\", \"'\"], true, false),\n peg$c61 = /^[0-9]/,\n peg$c62 = peg$classExpectation([[\"0\", \"9\"]], false, false),\n peg$c63 = function(a, b) {\n // Can use `a.flat().join('')` once supported\n const leadingDecimals = a ? [].concat.apply([], a).join('') : '';\n return { type: 'literal', value: parseFloat(leadingDecimals + b.join('')) };\n },\n peg$c64 = function(i) { return { type: 'literal', value: i }; },\n peg$c65 = \"type(\",\n peg$c66 = peg$literalExpectation(\"type(\", false),\n peg$c67 = /^[^ )]/,\n peg$c68 = peg$classExpectation([\" \", \")\"], true, false),\n peg$c69 = \")\",\n peg$c70 = peg$literalExpectation(\")\", false),\n peg$c71 = function(t) { return { type: 'type', value: t.join('') }; },\n peg$c72 = /^[imsu]/,\n peg$c73 = peg$classExpectation([\"i\", \"m\", \"s\", \"u\"], false, false),\n peg$c74 = \"/\",\n peg$c75 = peg$literalExpectation(\"/\", false),\n peg$c76 = function(pattern, flgs) {\n return {\n type: 'regexp', value: new RegExp(pattern.join(''), flgs ? flgs.join('') : '')\n };\n },\n peg$c77 = /^[^\\]\\\\]/,\n peg$c78 = peg$classExpectation([\"]\", \"\\\\\"], true, false),\n peg$c79 = function(cs) { return '[' + cs.join('') + ']'; },\n peg$c80 = function(a) { return '\\\\' + a; },\n peg$c81 = /^[^\\/\\\\[]/,\n peg$c82 = peg$classExpectation([\"/\", \"\\\\\", \"[\"], true, false),\n peg$c83 = function(cs) { return cs.join(''); },\n peg$c84 = function(i, is) {\n return { type: 'field', name: is.reduce(function(memo, p){ return memo + p[0] + p[1]; }, i)};\n },\n peg$c85 = \":not(\",\n peg$c86 = peg$literalExpectation(\":not(\", false),\n peg$c87 = function(ss) { return { type: 'not', selectors: ss }; },\n peg$c88 = \":matches(\",\n peg$c89 = peg$literalExpectation(\":matches(\", false),\n peg$c90 = function(ss) { return { type: 'matches', selectors: ss }; },\n peg$c91 = \":is(\",\n peg$c92 = peg$literalExpectation(\":is(\", false),\n peg$c93 = \":has(\",\n peg$c94 = peg$literalExpectation(\":has(\", false),\n peg$c95 = function(ss) { return { type: 'has', selectors: ss }; },\n peg$c96 = \":first-child\",\n peg$c97 = peg$literalExpectation(\":first-child\", false),\n peg$c98 = function() { return nth(1); },\n peg$c99 = \":last-child\",\n peg$c100 = peg$literalExpectation(\":last-child\", false),\n peg$c101 = function() { return nthLast(1); },\n peg$c102 = \":nth-child(\",\n peg$c103 = peg$literalExpectation(\":nth-child(\", false),\n peg$c104 = function(n) { return nth(parseInt(n.join(''), 10)); },\n peg$c105 = \":nth-last-child(\",\n peg$c106 = peg$literalExpectation(\":nth-last-child(\", false),\n peg$c107 = function(n) { return nthLast(parseInt(n.join(''), 10)); },\n peg$c108 = \":\",\n peg$c109 = peg$literalExpectation(\":\", false),\n peg$c110 = function(c) {\n return { type: 'class', name: c };\n },\n\n peg$currPos = 0,\n peg$savedPos = 0,\n peg$posDetailsCache = [{ line: 1, column: 1 }],\n peg$maxFailPos = 0,\n peg$maxFailExpected = [],\n peg$silentFails = 0,\n\n peg$resultsCache = {},\n\n peg$result;\n\n if (\"startRule\" in options) {\n if (!(options.startRule in peg$startRuleFunctions)) {\n throw new Error(\"Can't start parsing from rule \\\"\" + options.startRule + \"\\\".\");\n }\n\n peg$startRuleFunction = peg$startRuleFunctions[options.startRule];\n }\n\n function text() {\n return input.substring(peg$savedPos, peg$currPos);\n }\n\n function location() {\n return peg$computeLocation(peg$savedPos, peg$currPos);\n }\n\n function expected(description, location) {\n location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos)\n\n throw peg$buildStructuredError(\n [peg$otherExpectation(description)],\n input.substring(peg$savedPos, peg$currPos),\n location\n );\n }\n\n function error(message, location) {\n location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos)\n\n throw peg$buildSimpleError(message, location);\n }\n\n function peg$literalExpectation(text, ignoreCase) {\n return { type: \"literal\", text: text, ignoreCase: ignoreCase };\n }\n\n function peg$classExpectation(parts, inverted, ignoreCase) {\n return { type: \"class\", parts: parts, inverted: inverted, ignoreCase: ignoreCase };\n }\n\n function peg$anyExpectation() {\n return { type: \"any\" };\n }\n\n function peg$endExpectation() {\n return { type: \"end\" };\n }\n\n function peg$otherExpectation(description) {\n return { type: \"other\", description: description };\n }\n\n function peg$computePosDetails(pos) {\n var details = peg$posDetailsCache[pos], p;\n\n if (details) {\n return details;\n } else {\n p = pos - 1;\n while (!peg$posDetailsCache[p]) {\n p--;\n }\n\n details = peg$posDetailsCache[p];\n details = {\n line: details.line,\n column: details.column\n };\n\n while (p < pos) {\n if (input.charCodeAt(p) === 10) {\n details.line++;\n details.column = 1;\n } else {\n details.column++;\n }\n\n p++;\n }\n\n peg$posDetailsCache[pos] = details;\n return details;\n }\n }\n\n function peg$computeLocation(startPos, endPos) {\n var startPosDetails = peg$computePosDetails(startPos),\n endPosDetails = peg$computePosDetails(endPos);\n\n return {\n start: {\n offset: startPos,\n line: startPosDetails.line,\n column: startPosDetails.column\n },\n end: {\n offset: endPos,\n line: endPosDetails.line,\n column: endPosDetails.column\n }\n };\n }\n\n function peg$fail(expected) {\n if (peg$currPos < peg$maxFailPos) { return; }\n\n if (peg$currPos > peg$maxFailPos) {\n peg$maxFailPos = peg$currPos;\n peg$maxFailExpected = [];\n }\n\n peg$maxFailExpected.push(expected);\n }\n\n function peg$buildSimpleError(message, location) {\n return new peg$SyntaxError(message, null, null, location);\n }\n\n function peg$buildStructuredError(expected, found, location) {\n return new peg$SyntaxError(\n peg$SyntaxError.buildMessage(expected, found),\n expected,\n found,\n location\n );\n }\n\n function peg$parsestart() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 36 + 0,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n s2 = peg$parseselectors();\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c0(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c1();\n }\n s0 = s1;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parse_() {\n var s0, s1;\n\n var key = peg$currPos * 36 + 1,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = [];\n if (input.charCodeAt(peg$currPos) === 32) {\n s1 = peg$c2;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c3); }\n }\n while (s1 !== peg$FAILED) {\n s0.push(s1);\n if (input.charCodeAt(peg$currPos) === 32) {\n s1 = peg$c2;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c3); }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseidentifierName() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 2,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = [];\n if (peg$c4.test(input.charAt(peg$currPos))) {\n s2 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c5); }\n }\n if (s2 !== peg$FAILED) {\n while (s2 !== peg$FAILED) {\n s1.push(s2);\n if (peg$c4.test(input.charAt(peg$currPos))) {\n s2 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c5); }\n }\n }\n } else {\n s1 = peg$FAILED;\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c6(s1);\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsebinaryOp() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 36 + 3,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 62) {\n s2 = peg$c7;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c8); }\n }\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c9();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 126) {\n s2 = peg$c10;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c11); }\n }\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c12();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 43) {\n s2 = peg$c13;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c14); }\n }\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c15();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 32) {\n s1 = peg$c2;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c3); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c16();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsehasSelectors() {\n var s0, s1, s2, s3, s4, s5, s6, s7;\n\n var key = peg$currPos * 36 + 4,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parsehasSelector();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parsehasSelector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parsehasSelector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c19(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseselectors() {\n var s0, s1, s2, s3, s4, s5, s6, s7;\n\n var key = peg$currPos * 36 + 5,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseselector();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parseselector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parseselector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c19(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsehasSelector() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 6,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parsebinaryOp();\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseselector();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c20(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseselector() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 7,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parsesequence();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n s4 = peg$parsebinaryOp();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsesequence();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n s4 = peg$parsebinaryOp();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsesequence();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c21(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsesequence() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 36 + 8,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 33) {\n s1 = peg$c22;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c23); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$parseatom();\n if (s3 !== peg$FAILED) {\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$parseatom();\n }\n } else {\n s2 = peg$FAILED;\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c24(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseatom() {\n var s0;\n\n var key = peg$currPos * 36 + 9,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$parsewildcard();\n if (s0 === peg$FAILED) {\n s0 = peg$parseidentifier();\n if (s0 === peg$FAILED) {\n s0 = peg$parseattr();\n if (s0 === peg$FAILED) {\n s0 = peg$parsefield();\n if (s0 === peg$FAILED) {\n s0 = peg$parsenegation();\n if (s0 === peg$FAILED) {\n s0 = peg$parsematches();\n if (s0 === peg$FAILED) {\n s0 = peg$parseis();\n if (s0 === peg$FAILED) {\n s0 = peg$parsehas();\n if (s0 === peg$FAILED) {\n s0 = peg$parsefirstChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parselastChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parsenthChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parsenthLastChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parseclass();\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsewildcard() {\n var s0, s1;\n\n var key = peg$currPos * 36 + 10,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 42) {\n s1 = peg$c25;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c26); }\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c27(s1);\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseidentifier() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 11,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 35) {\n s1 = peg$c28;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c29); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseidentifierName();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c30(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattr() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 12,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 91) {\n s1 = peg$c31;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c32); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseattrValue();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 93) {\n s5 = peg$c33;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c34); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c35(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrOps() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 13,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (peg$c36.test(input.charAt(peg$currPos))) {\n s1 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c37); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 61) {\n s2 = peg$c38;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c39); }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c40(s1);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n if (peg$c41.test(input.charAt(peg$currPos))) {\n s0 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s0 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c42); }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrEqOps() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 14,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 33) {\n s1 = peg$c22;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c23); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 61) {\n s2 = peg$c38;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c39); }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c40(s1);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrName() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 15,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseidentifierName();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s4 = peg$c43;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s4 !== peg$FAILED) {\n s5 = peg$parseidentifierName();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s4 = peg$c43;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s4 !== peg$FAILED) {\n s5 = peg$parseidentifierName();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c45(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrValue() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 16,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseattrName();\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseattrEqOps();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsetype();\n if (s5 === peg$FAILED) {\n s5 = peg$parseregex();\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c46(s1, s3, s5);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parseattrName();\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseattrOps();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsestring();\n if (s5 === peg$FAILED) {\n s5 = peg$parsenumber();\n if (s5 === peg$FAILED) {\n s5 = peg$parsepath();\n }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c46(s1, s3, s5);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parseattrName();\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c47(s1);\n }\n s0 = s1;\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsestring() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 17,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 34) {\n s1 = peg$c48;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c49); }\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c50.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c51); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c50.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c51); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 34) {\n s3 = peg$c48;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c49); }\n }\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c56(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 39) {\n s1 = peg$c57;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c58); }\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c59.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c60); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c59.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c60); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 39) {\n s3 = peg$c57;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c58); }\n }\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c56(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenumber() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 36 + 18,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$currPos;\n s2 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 46) {\n s3 = peg$c43;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s3 !== peg$FAILED) {\n s2 = [s2, s3];\n s1 = s2;\n } else {\n peg$currPos = s1;\n s1 = peg$FAILED;\n }\n } else {\n peg$currPos = s1;\n s1 = peg$FAILED;\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n if (s3 !== peg$FAILED) {\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n } else {\n s2 = peg$FAILED;\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c63(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsepath() {\n var s0, s1;\n\n var key = peg$currPos * 36 + 19,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseidentifierName();\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c64(s1);\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsetype() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 20,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 5) === peg$c65) {\n s1 = peg$c65;\n peg$currPos += 5;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c66); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = [];\n if (peg$c67.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c68); }\n }\n if (s4 !== peg$FAILED) {\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n if (peg$c67.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c68); }\n }\n }\n } else {\n s3 = peg$FAILED;\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c71(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseflags() {\n var s0, s1;\n\n var key = peg$currPos * 36 + 21,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = [];\n if (peg$c72.test(input.charAt(peg$currPos))) {\n s1 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c73); }\n }\n if (s1 !== peg$FAILED) {\n while (s1 !== peg$FAILED) {\n s0.push(s1);\n if (peg$c72.test(input.charAt(peg$currPos))) {\n s1 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c73); }\n }\n }\n } else {\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseregex() {\n var s0, s1, s2, s3, s4;\n\n var key = peg$currPos * 36 + 22,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 47) {\n s1 = peg$c74;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c75); }\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$parsere_character_class();\n if (s3 === peg$FAILED) {\n s3 = peg$parsere_escape();\n if (s3 === peg$FAILED) {\n s3 = peg$parsere_chars();\n }\n }\n if (s3 !== peg$FAILED) {\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$parsere_character_class();\n if (s3 === peg$FAILED) {\n s3 = peg$parsere_escape();\n if (s3 === peg$FAILED) {\n s3 = peg$parsere_chars();\n }\n }\n }\n } else {\n s2 = peg$FAILED;\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 47) {\n s3 = peg$c74;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c75); }\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parseflags();\n if (s4 === peg$FAILED) {\n s4 = null;\n }\n if (s4 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c76(s2, s4);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsere_character_class() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 36 + 23,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 91) {\n s1 = peg$c31;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c32); }\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c77.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c78); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$parsere_escape();\n }\n if (s3 !== peg$FAILED) {\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c77.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c78); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$parsere_escape();\n }\n }\n } else {\n s2 = peg$FAILED;\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 93) {\n s3 = peg$c33;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c34); }\n }\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c79(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsere_escape() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 24,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s1 = peg$c52;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s1 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s2 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c80(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsere_chars() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 25,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = [];\n if (peg$c81.test(input.charAt(peg$currPos))) {\n s2 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c82); }\n }\n if (s2 !== peg$FAILED) {\n while (s2 !== peg$FAILED) {\n s1.push(s2);\n if (peg$c81.test(input.charAt(peg$currPos))) {\n s2 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c82); }\n }\n }\n } else {\n s1 = peg$FAILED;\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c83(s1);\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsefield() {\n var s0, s1, s2, s3, s4, s5, s6;\n\n var key = peg$currPos * 36 + 26,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s1 = peg$c43;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseidentifierName();\n if (s2 !== peg$FAILED) {\n s3 = [];\n s4 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s5 = peg$c43;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parseidentifierName();\n if (s6 !== peg$FAILED) {\n s5 = [s5, s6];\n s4 = s5;\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n s4 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s5 = peg$c43;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parseidentifierName();\n if (s6 !== peg$FAILED) {\n s5 = [s5, s6];\n s4 = s5;\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n }\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c84(s2, s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenegation() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 27,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 5) === peg$c85) {\n s1 = peg$c85;\n peg$currPos += 5;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c86); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseselectors();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c87(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsematches() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 28,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 9) === peg$c88) {\n s1 = peg$c88;\n peg$currPos += 9;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c89); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseselectors();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c90(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseis() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 29,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 4) === peg$c91) {\n s1 = peg$c91;\n peg$currPos += 4;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c92); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseselectors();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c90(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsehas() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 30,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 5) === peg$c93) {\n s1 = peg$c93;\n peg$currPos += 5;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c94); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parsehasSelectors();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c95(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsefirstChild() {\n var s0, s1;\n\n var key = peg$currPos * 36 + 31,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 12) === peg$c96) {\n s1 = peg$c96;\n peg$currPos += 12;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c97); }\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c98();\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parselastChild() {\n var s0, s1;\n\n var key = peg$currPos * 36 + 32,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 11) === peg$c99) {\n s1 = peg$c99;\n peg$currPos += 11;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c100); }\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c101();\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenthChild() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 33,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 11) === peg$c102) {\n s1 = peg$c102;\n peg$currPos += 11;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c103); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n if (s4 !== peg$FAILED) {\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n } else {\n s3 = peg$FAILED;\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c104(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenthLastChild() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 34,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 16) === peg$c105) {\n s1 = peg$c105;\n peg$currPos += 16;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c106); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n if (s4 !== peg$FAILED) {\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n } else {\n s3 = peg$FAILED;\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c107(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseclass() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 35,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 58) {\n s1 = peg$c108;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c109); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseidentifierName();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c110(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n\n function nth(n) { return { type: 'nth-child', index: { type: 'literal', value: n } }; }\n function nthLast(n) { return { type: 'nth-last-child', index: { type: 'literal', value: n } }; }\n function strUnescape(s) {\n return s.replace(/\\\\(.)/g, function(match, ch) {\n switch(ch) {\n case 'b': return '\\b';\n case 'f': return '\\f';\n case 'n': return '\\n';\n case 'r': return '\\r';\n case 't': return '\\t';\n case 'v': return '\\v';\n default: return ch;\n }\n });\n }\n\n\n peg$result = peg$startRuleFunction();\n\n if (peg$result !== peg$FAILED && peg$currPos === input.length) {\n return peg$result;\n } else {\n if (peg$result !== peg$FAILED && peg$currPos < input.length) {\n peg$fail(peg$endExpectation());\n }\n\n throw peg$buildStructuredError(\n peg$maxFailExpected,\n peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null,\n peg$maxFailPos < input.length\n ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1)\n : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)\n );\n }\n }\n\n return {\n SyntaxError: peg$SyntaxError,\n parse: peg$parse\n };\n});\n","/* vim: set sw=4 sts=4 : */\nimport estraverse from 'estraverse';\nimport parser from './parser.js';\n\n/**\n* @typedef {\"LEFT_SIDE\"|\"RIGHT_SIDE\"} Side\n*/\n\nconst LEFT_SIDE = 'LEFT_SIDE';\nconst RIGHT_SIDE = 'RIGHT_SIDE';\n\n/**\n * @external AST\n * @see https://esprima.readthedocs.io/en/latest/syntax-tree-format.html\n */\n\n/**\n * One of the rules of `grammar.pegjs`\n * @typedef {PlainObject} SelectorAST\n * @see grammar.pegjs\n*/\n\n/**\n * The `sequence` production of `grammar.pegjs`\n * @typedef {PlainObject} SelectorSequenceAST\n*/\n\n/**\n * Get the value of a property which may be multiple levels down\n * in the object.\n * @param {?PlainObject} obj\n * @param {string[]} keys\n * @returns {undefined|boolean|string|number|external:AST}\n */\nfunction getPath(obj, keys) {\n for (let i = 0; i < keys.length; ++i) {\n if (obj == null) { return obj; }\n obj = obj[keys[i]];\n }\n return obj;\n}\n\n/**\n * Determine whether `node` can be reached by following `path`,\n * starting at `ancestor`.\n * @param {?external:AST} node\n * @param {?external:AST} ancestor\n * @param {string[]} path\n * @param {Integer} fromPathIndex\n * @returns {boolean}\n */\nfunction inPath(node, ancestor, path, fromPathIndex) {\n let current = ancestor;\n for (let i = fromPathIndex; i < path.length; ++i) {\n if (current == null) {\n return false;\n }\n const field = current[path[i]];\n if (Array.isArray(field)) {\n for (let k = 0; k < field.length; ++k) {\n if (inPath(node, field[k], path, i + 1)) {\n return true;\n }\n }\n return false;\n }\n current = field;\n }\n return node === current;\n}\n\n/**\n * A generated matcher function for a selector.\n * @callback SelectorMatcher\n * @param {?SelectorAST} selector\n * @param {external:AST[]} [ancestry=[]]\n * @param {ESQueryOptions} [options]\n * @returns {void}\n*/\n\n/**\n * A WeakMap for holding cached matcher functions for selectors.\n * @type {WeakMap}\n*/\nconst MATCHER_CACHE = typeof WeakMap === 'function' ? new WeakMap : null;\n\n/**\n * Look up a matcher function for `selector` in the cache.\n * If it does not exist, generate it with `generateMatcher` and add it to the cache.\n * In engines without WeakMap, the caching is skipped and matchers are generated with every call.\n * @param {?SelectorAST} selector\n * @returns {SelectorMatcher}\n */\nfunction getMatcher(selector) {\n if (selector == null) {\n return () => true;\n }\n\n if (MATCHER_CACHE != null) {\n let matcher = MATCHER_CACHE.get(selector);\n if (matcher != null) {\n return matcher;\n }\n matcher = generateMatcher(selector);\n MATCHER_CACHE.set(selector, matcher);\n return matcher;\n }\n\n return generateMatcher(selector);\n}\n\n/**\n * Create a matcher function for `selector`,\n * @param {?SelectorAST} selector\n * @returns {SelectorMatcher}\n */\nfunction generateMatcher(selector) {\n switch(selector.type) {\n case 'wildcard':\n return () => true;\n\n case 'identifier': {\n const value = selector.value.toLowerCase();\n return (node, ancestry, options) => {\n const nodeTypeKey = (options && options.nodeTypeKey) || 'type';\n return value === node[nodeTypeKey].toLowerCase();\n };\n }\n\n case 'exactNode':\n return (node, ancestry) => {\n return ancestry.length === 0;\n };\n\n case 'field': {\n const path = selector.name.split('.');\n return (node, ancestry) => {\n const ancestor = ancestry[path.length - 1];\n return inPath(node, ancestor, path, 0);\n };\n }\n\n case 'matches': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n for (let i = 0; i < matchers.length; ++i) {\n if (matchers[i](node, ancestry, options)) { return true; }\n }\n return false;\n };\n }\n\n case 'compound': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n for (let i = 0; i < matchers.length; ++i) {\n if (!matchers[i](node, ancestry, options)) { return false; }\n }\n return true;\n };\n }\n\n case 'not': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n for (let i = 0; i < matchers.length; ++i) {\n if (matchers[i](node, ancestry, options)) { return false; }\n }\n return true;\n };\n }\n\n case 'has': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n let result = false;\n\n const a = [];\n estraverse.traverse(node, {\n enter (node, parent) {\n if (parent != null) { a.unshift(parent); }\n\n for (let i = 0; i < matchers.length; ++i) {\n if (matchers[i](node, a, options)) {\n result = true;\n this.break();\n return;\n }\n }\n },\n leave () { a.shift(); },\n keys: options && options.visitorKeys,\n fallback: options && options.fallback || 'iteration'\n });\n\n return result;\n };\n }\n\n case 'child': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) => {\n if (ancestry.length > 0 && right(node, ancestry, options)) {\n return left(ancestry[0], ancestry.slice(1), options);\n }\n return false;\n };\n }\n\n case 'descendant': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) => {\n if (right(node, ancestry, options)) {\n for (let i = 0, l = ancestry.length; i < l; ++i) {\n if (left(ancestry[i], ancestry.slice(i + 1), options)) {\n return true;\n }\n }\n }\n return false;\n };\n }\n\n case 'attribute': {\n const path = selector.name.split('.');\n switch (selector.operator) {\n case void 0:\n return (node) => getPath(node, path) != null;\n case '=':\n switch (selector.value.type) {\n case 'regexp':\n return (node) => {\n const p = getPath(node, path);\n return typeof p === 'string' && selector.value.value.test(p);\n };\n case 'literal': {\n const literal = `${selector.value.value}`;\n return (node) => literal === `${getPath(node, path)}`;\n }\n case 'type':\n return (node) => selector.value.value === typeof getPath(node, path);\n }\n throw new Error(`Unknown selector value type: ${selector.value.type}`);\n case '!=':\n switch (selector.value.type) {\n case 'regexp':\n return (node) => !selector.value.value.test(getPath(node, path));\n case 'literal': {\n const literal = `${selector.value.value}`;\n return (node) => literal !== `${getPath(node, path)}`;\n }\n case 'type':\n return (node) => selector.value.value !== typeof getPath(node, path);\n }\n throw new Error(`Unknown selector value type: ${selector.value.type}`);\n case '<=':\n return (node) => getPath(node, path) <= selector.value.value;\n case '<':\n return (node) => getPath(node, path) < selector.value.value;\n case '>':\n return (node) => getPath(node, path) > selector.value.value;\n case '>=':\n return (node) => getPath(node, path) >= selector.value.value;\n }\n throw new Error(`Unknown operator: ${selector.operator}`);\n }\n\n case 'sibling': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n sibling(node, left, ancestry, LEFT_SIDE, options) ||\n selector.left.subject &&\n left(node, ancestry, options) &&\n sibling(node, right, ancestry, RIGHT_SIDE, options);\n }\n\n case 'adjacent': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n adjacent(node, left, ancestry, LEFT_SIDE, options) ||\n selector.right.subject &&\n left(node, ancestry, options) &&\n adjacent(node, right, ancestry, RIGHT_SIDE, options);\n }\n\n case 'nth-child': {\n const nth = selector.index.value;\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n nthChild(node, ancestry, nth, options);\n }\n\n case 'nth-last-child': {\n const nth = -selector.index.value;\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n nthChild(node, ancestry, nth, options);\n }\n\n case 'class': {\n \n const name = selector.name.toLowerCase();\n\n return (node, ancestry, options) => {\n \n if (options && options.matchClass) {\n return options.matchClass(selector.name, node, ancestry);\n }\n \n if (options && options.nodeTypeKey) return false; \n\n switch(name){\n case 'statement':\n if(node.type.slice(-9) === 'Statement') return true;\n // fallthrough: interface Declaration <: Statement { }\n case 'declaration':\n return node.type.slice(-11) === 'Declaration';\n case 'pattern':\n if(node.type.slice(-7) === 'Pattern') return true;\n // fallthrough: interface Expression <: Node, Pattern { }\n case 'expression':\n return node.type.slice(-10) === 'Expression' ||\n node.type.slice(-7) === 'Literal' ||\n (\n node.type === 'Identifier' &&\n (ancestry.length === 0 || ancestry[0].type !== 'MetaProperty')\n ) ||\n node.type === 'MetaProperty';\n case 'function':\n return node.type === 'FunctionDeclaration' ||\n node.type === 'FunctionExpression' ||\n node.type === 'ArrowFunctionExpression';\n }\n throw new Error(`Unknown class name: ${selector.name}`);\n };\n }\n }\n\n throw new Error(`Unknown selector type: ${selector.type}`);\n}\n\n/**\n * @callback TraverseOptionFallback\n * @param {external:AST} node The given node.\n * @returns {string[]} An array of visitor keys for the given node.\n */\n\n/**\n * @callback ClassMatcher\n * @param {string} className The name of the class to match.\n * @param {external:AST} node The node to match against.\n * @param {Array} ancestry The ancestry of the node.\n * @returns {boolean} True if the node matches the class, false if not.\n */\n\n/**\n * @typedef {object} ESQueryOptions\n * @property {string} [nodeTypeKey=\"type\"] By passing `nodeTypeKey`, we can allow other ASTs to use ESQuery.\n * @property { { [nodeType: string]: string[] } } [visitorKeys] By passing `visitorKeys` mapping, we can extend the properties of the nodes that traverse the node.\n * @property {TraverseOptionFallback} [fallback] By passing `fallback` option, we can control the properties of traversing nodes when encountering unknown nodes.\n * @property {ClassMatcher} [matchClass] By passing `matchClass` option, we can customize the interpretation of classes.\n */\n\n/**\n * Given a `node` and its ancestors, determine if `node` is matched\n * by `selector`.\n * @param {?external:AST} node\n * @param {?SelectorAST} selector\n * @param {external:AST[]} [ancestry=[]]\n * @param {ESQueryOptions} [options]\n * @throws {Error} Unknowns (operator, class name, selector type, or\n * selector value type)\n * @returns {boolean}\n */\nfunction matches(node, selector, ancestry, options) {\n if (!selector) { return true; }\n if (!node) { return false; }\n if (!ancestry) { ancestry = []; }\n\n return getMatcher(selector)(node, ancestry, options);\n}\n\n/**\n * Get visitor keys of a given node.\n * @param {external:AST} node The AST node to get keys.\n * @param {ESQueryOptions|undefined} options\n * @returns {string[]} Visitor keys of the node.\n */\nfunction getVisitorKeys(node, options) {\n const nodeTypeKey = (options && options.nodeTypeKey) || 'type';\n\n const nodeType = node[nodeTypeKey];\n if (options && options.visitorKeys && options.visitorKeys[nodeType]) {\n return options.visitorKeys[nodeType];\n }\n if (estraverse.VisitorKeys[nodeType]) {\n return estraverse.VisitorKeys[nodeType];\n }\n if (options && typeof options.fallback === 'function') {\n return options.fallback(node);\n }\n // 'iteration' fallback\n return Object.keys(node).filter(function (key) {\n return key !== nodeTypeKey;\n });\n}\n\n\n/**\n * Check whether the given value is an ASTNode or not.\n * @param {any} node The value to check.\n * @param {ESQueryOptions|undefined} options The options to use.\n * @returns {boolean} `true` if the value is an ASTNode.\n */\nfunction isNode(node, options) {\n const nodeTypeKey = (options && options.nodeTypeKey) || 'type';\n return node !== null && typeof node === 'object' && typeof node[nodeTypeKey] === 'string';\n}\n\n/**\n * Determines if the given node has a sibling that matches the\n * given selector matcher.\n * @param {external:AST} node\n * @param {SelectorMatcher} matcher\n * @param {external:AST[]} ancestry\n * @param {Side} side\n * @param {ESQueryOptions|undefined} options\n * @returns {boolean}\n */\nfunction sibling(node, matcher, ancestry, side, options) {\n const [parent] = ancestry;\n if (!parent) { return false; }\n const keys = getVisitorKeys(parent, options);\n for (let i = 0; i < keys.length; ++i) {\n const listProp = parent[keys[i]];\n if (Array.isArray(listProp)) {\n const startIndex = listProp.indexOf(node);\n if (startIndex < 0) { continue; }\n let lowerBound, upperBound;\n if (side === LEFT_SIDE) {\n lowerBound = 0;\n upperBound = startIndex;\n } else {\n lowerBound = startIndex + 1;\n upperBound = listProp.length;\n }\n for (let k = lowerBound; k < upperBound; ++k) {\n if (isNode(listProp[k], options) && matcher(listProp[k], ancestry, options)) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\n/**\n * Determines if the given node has an adjacent sibling that matches\n * the given selector matcher.\n * @param {external:AST} node\n * @param {SelectorMatcher} matcher\n * @param {external:AST[]} ancestry\n * @param {Side} side\n * @param {ESQueryOptions|undefined} options\n * @returns {boolean}\n */\nfunction adjacent(node, matcher, ancestry, side, options) {\n const [parent] = ancestry;\n if (!parent) { return false; }\n const keys = getVisitorKeys(parent, options);\n for (let i = 0; i < keys.length; ++i) {\n const listProp = parent[keys[i]];\n if (Array.isArray(listProp)) {\n const idx = listProp.indexOf(node);\n if (idx < 0) { continue; }\n if (side === LEFT_SIDE && idx > 0 && isNode(listProp[idx - 1], options) && matcher(listProp[idx - 1], ancestry, options)) {\n return true;\n }\n if (side === RIGHT_SIDE && idx < listProp.length - 1 && isNode(listProp[idx + 1], options) && matcher(listProp[idx + 1], ancestry, options)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Determines if the given node is the `nth` child.\n * If `nth` is negative then the position is counted\n * from the end of the list of children.\n * @param {external:AST} node\n * @param {external:AST[]} ancestry\n * @param {Integer} nth\n * @param {ESQueryOptions|undefined} options\n * @returns {boolean}\n */\nfunction nthChild(node, ancestry, nth, options) {\n if (nth === 0) { return false; }\n const [parent] = ancestry;\n if (!parent) { return false; }\n const keys = getVisitorKeys(parent, options);\n for (let i = 0; i < keys.length; ++i) {\n const listProp = parent[keys[i]];\n if (Array.isArray(listProp)){\n const idx = nth < 0 ? listProp.length + nth : nth - 1;\n if (idx >= 0 && idx < listProp.length && listProp[idx] === node) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * For each selector node marked as a subject, find the portion of the\n * selector that the subject must match.\n * @param {SelectorAST} selector\n * @param {SelectorAST} [ancestor] Defaults to `selector`\n * @returns {SelectorAST[]}\n */\nfunction subjects(selector, ancestor) {\n if (selector == null || typeof selector != 'object') { return []; }\n if (ancestor == null) { ancestor = selector; }\n const results = selector.subject ? [ancestor] : [];\n const keys = Object.keys(selector);\n for (let i = 0; i < keys.length; ++i) {\n const p = keys[i];\n const sel = selector[p];\n results.push(...subjects(sel, p === 'left' ? sel : ancestor));\n }\n return results;\n}\n\n/**\n* @callback TraverseVisitor\n* @param {?external:AST} node\n* @param {?external:AST} parent\n* @param {external:AST[]} ancestry\n*/\n\n/**\n * From a JS AST and a selector AST, collect all JS AST nodes that\n * match the selector.\n * @param {external:AST} ast\n * @param {?SelectorAST} selector\n * @param {TraverseVisitor} visitor\n * @param {ESQueryOptions} [options]\n * @returns {external:AST[]}\n */\nfunction traverse(ast, selector, visitor, options) {\n if (!selector) { return; }\n const ancestry = [];\n const matcher = getMatcher(selector);\n const altSubjects = subjects(selector).map(getMatcher);\n estraverse.traverse(ast, {\n enter (node, parent) {\n if (parent != null) { ancestry.unshift(parent); }\n if (matcher(node, ancestry, options)) {\n if (altSubjects.length) {\n for (let i = 0, l = altSubjects.length; i < l; ++i) {\n if (altSubjects[i](node, ancestry, options)) {\n visitor(node, parent, ancestry);\n }\n for (let k = 0, m = ancestry.length; k < m; ++k) {\n const succeedingAncestry = ancestry.slice(k + 1);\n if (altSubjects[i](ancestry[k], succeedingAncestry, options)) {\n visitor(ancestry[k], parent, succeedingAncestry);\n }\n }\n }\n } else {\n visitor(node, parent, ancestry);\n }\n }\n },\n leave () { ancestry.shift(); },\n keys: options && options.visitorKeys,\n fallback: options && options.fallback || 'iteration'\n });\n}\n\n\n/**\n * From a JS AST and a selector AST, collect all JS AST nodes that\n * match the selector.\n * @param {external:AST} ast\n * @param {?SelectorAST} selector\n * @param {ESQueryOptions} [options]\n * @returns {external:AST[]}\n */\nfunction match(ast, selector, options) {\n const results = [];\n traverse(ast, selector, function (node) {\n results.push(node);\n }, options);\n return results;\n}\n\n/**\n * Parse a selector string and return its AST.\n * @param {string} selector\n * @returns {SelectorAST}\n */\nfunction parse(selector) {\n return parser.parse(selector);\n}\n\n/**\n * Query the code AST using the selector string.\n * @param {external:AST} ast\n * @param {string} selector\n * @param {ESQueryOptions} [options]\n * @returns {external:AST[]}\n */\nfunction query(ast, selector, options) {\n return match(ast, parse(selector), options);\n}\n\nquery.parse = parse;\nquery.match = match;\nquery.traverse = traverse;\nquery.matches = matches;\nquery.query = query;\n\nexport default query;\n"],"names":["clone","exports","Syntax","VisitorOption","VisitorKeys","BREAK","SKIP","REMOVE","deepCopy","obj","key","val","ret","hasOwnProperty","Reference","parent","this","Element","node","path","wrap","ref","Controller","isNode","type","isProperty","nodeType","ObjectExpression","ObjectPattern","candidateExistsInLeaveList","leavelist","candidate","i","length","traverse","root","visitor","extendCommentRange","comment","tokens","target","array","func","diff","len","current","upperBound","token","range","extendedRange","AssignmentExpression","AssignmentPattern","ArrayExpression","ArrayPattern","ArrowFunctionExpression","AwaitExpression","BlockStatement","BinaryExpression","BreakStatement","CallExpression","CatchClause","ChainExpression","ClassBody","ClassDeclaration","ClassExpression","ComprehensionBlock","ComprehensionExpression","ConditionalExpression","ContinueStatement","DebuggerStatement","DirectiveStatement","DoWhileStatement","EmptyStatement","ExportAllDeclaration","ExportDefaultDeclaration","ExportNamedDeclaration","ExportSpecifier","ExpressionStatement","ForStatement","ForInStatement","ForOfStatement","FunctionDeclaration","FunctionExpression","GeneratorExpression","Identifier","IfStatement","ImportExpression","ImportDeclaration","ImportDefaultSpecifier","ImportNamespaceSpecifier","ImportSpecifier","Literal","LabeledStatement","LogicalExpression","MemberExpression","MetaProperty","MethodDefinition","ModuleSpecifier","NewExpression","PrivateIdentifier","Program","Property","PropertyDefinition","RestElement","ReturnStatement","SequenceExpression","SpreadElement","Super","SwitchStatement","SwitchCase","TaggedTemplateExpression","TemplateElement","TemplateLiteral","ThisExpression","ThrowStatement","TryStatement","UnaryExpression","UpdateExpression","VariableDeclaration","VariableDeclarator","WhileStatement","WithStatement","YieldExpression","Break","Skip","Remove","prototype","replace","remove","Array","isArray","splice","iz","j","jz","result","addToPath","push","__current","__leavelist","parents","__execute","callback","element","previous","undefined","__state","call","notify","flag","skip","__initialize","__worklist","__fallback","fallback","Object","keys","__keys","assign","create","worklist","current2","candidates","sentinel","pop","enter","Error","leave","outer","removeElem","nextElem","attachComments","tree","providedComments","cursor","comments","leadingComments","trailingComments","cloneEnvironment","module","peg$SyntaxError","message","expected","found","location","name","captureStackTrace","child","ctor","constructor","peg$subclass","buildMessage","DESCRIBE_EXPECTATION_FNS","literal","expectation","literalEscape","text","class","escapedParts","parts","classEscape","inverted","any","end","other","description","hex","ch","charCodeAt","toString","toUpperCase","s","descriptions","sort","slice","join","describeExpected","describeFound","SyntaxError","parse","input","options","peg$result","peg$FAILED","peg$startRuleFunctions","start","peg$parsestart","peg$startRuleFunction","peg$c3","peg$literalExpectation","peg$c4","peg$c5","peg$classExpectation","peg$c8","peg$c11","peg$c14","peg$c18","peg$c19","ss","concat","map","peg$c23","peg$c26","peg$c29","peg$c32","peg$c34","peg$c36","peg$c37","peg$c39","peg$c40","a","peg$c41","peg$c42","peg$c44","peg$c46","op","value","operator","peg$c49","peg$c50","peg$c51","peg$c53","peg$c54","peg$c55","b","peg$c56","d","match","peg$c58","peg$c59","peg$c60","peg$c61","peg$c62","peg$c66","peg$c67","peg$c68","peg$c70","peg$c72","peg$c73","peg$c75","peg$c77","peg$c78","peg$c81","peg$c82","peg$c86","peg$c89","peg$c90","selectors","peg$c92","peg$c94","peg$c97","peg$c100","peg$c103","peg$c106","peg$c109","peg$currPos","peg$posDetailsCache","line","column","peg$maxFailPos","peg$maxFailExpected","peg$silentFails","startRule","ignoreCase","peg$computePosDetails","pos","p","details","peg$computeLocation","startPos","endPos","startPosDetails","endPosDetails","offset","peg$fail","s0","s1","s2","cached","peg$resultsCache","nextPos","peg$parse_","peg$parseselectors","peg$c1","peg$parseidentifierName","test","charAt","peg$parsebinaryOp","s3","s4","s5","s6","s7","peg$parseselector","peg$parsehasSelector","left","right","peg$parsesequence","reduce","memo","rhs","subject","as","peg$parseatom","peg$parsewildcard","peg$parseidentifier","peg$parseattrName","peg$parseattrEqOps","substr","peg$parsetype","flgs","peg$parsere_character_class","peg$parsere_escape","peg$parsere_chars","peg$parseflags","RegExp","peg$parseregex","peg$parseattrOps","peg$parsestring","leadingDecimals","apply","parseFloat","peg$parsenumber","peg$parsepath","peg$parseattrValue","peg$parseattr","peg$parsefield","peg$parsenegation","peg$parsematches","peg$parseis","peg$parsehasSelectors","peg$parsehas","nth","peg$parsefirstChild","nthLast","peg$parselastChild","parseInt","peg$parsenthChild","peg$parsenthLastChild","peg$parseclass","n","index","factory","getPath","MATCHER_CACHE","WeakMap","getMatcher","selector","matcher","get","generateMatcher","set","toLowerCase","ancestry","nodeTypeKey","split","inPath","ancestor","fromPathIndex","field","k","matchers","estraverse","unshift","shift","visitorKeys","l","_typeof","sibling","adjacent","nthChild","matchClass","getVisitorKeys","filter","side","_slicedToArray","listProp","startIndex","indexOf","lowerBound","idx","ast","altSubjects","subjects","results","sel","_toConsumableArray","m","succeedingAncestry","parser","query","matches"],"mappings":"qzDA2BC,SAASA,EAAMC,GAGZ,IAAIC,EACAC,EACAC,EACAC,EACAC,EACAC,EAEJ,SAASC,EAASC,GACd,IAAcC,EAAKC,EAAfC,EAAM,GACV,IAAKF,KAAOD,EACJA,EAAII,eAAeH,KACnBC,EAAMF,EAAIC,GAENE,EAAIF,GADW,iBAARC,GAA4B,OAARA,EAChBH,EAASG,GAETA,GAIvB,OAAOC,EAgMX,SAASE,EAAUC,EAAQL,GACvBM,KAAKD,OAASA,EACdC,KAAKN,IAAMA,EAiBf,SAASO,EAAQC,EAAMC,EAAMC,EAAMC,GAC/BL,KAAKE,KAAOA,EACZF,KAAKG,KAAOA,EACZH,KAAKI,KAAOA,EACZJ,KAAKK,IAAMA,EAGf,SAASC,KAuHT,SAASC,EAAOL,GACZ,OAAY,MAARA,IAGmB,iBAATA,GAA0C,iBAAdA,EAAKM,MAGnD,SAASC,EAAWC,EAAUhB,GAC1B,OAAQgB,IAAaxB,EAAOyB,kBAAoBD,IAAaxB,EAAO0B,gBAAkB,eAAiBlB,EAG3G,SAASmB,EAA2BC,EAAWC,GAC3C,IAAK,IAAIC,EAAIF,EAAUG,OAAS,EAAGD,GAAK,IAAKA,EACzC,GAAIF,EAAUE,GAAGd,OAASa,EACtB,OAAO,EAGf,OAAO,EAwQX,SAASG,EAASC,EAAMC,GAEpB,OADiB,IAAId,GACHY,SAASC,EAAMC,GAQrC,SAASC,EAAmBC,EAASC,GACjC,IAAIC,EAiBJ,OAfAA,EAjnBJ,SAAoBC,EAAOC,GACvB,IAAIC,EAAMC,EAAKZ,EAAGa,EAKlB,IAHAD,EAAMH,EAAMR,OACZD,EAAI,EAEGY,GAGCF,EAAKD,EADTI,EAAUb,GADVW,EAAOC,IAAQ,KAGXA,EAAMD,GAENX,EAAIa,EAAU,EACdD,GAAOD,EAAO,GAG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,CAC7C,IAAM4B,EAAqBnC,EAASnL,MAAM0L,EAAI,GAC1CsB,EAAYtY,GAAGyW,EAASO,GAAI4B,EAAoB/M,IAChDzL,EAAQqW,EAASO,GAAIjY,EAAQ6Z,SAKzCxY,EAAQlB,EAAMH,EAAQ0X,IAIlClO,iBAAWkO,EAASW,SACpBxP,KAAMiE,GAAWA,EAAQwL,YACzB3P,SAAUmE,GAAWA,EAAQnE,UAAY,eAajD,SAASiH,EAAM0J,EAAKlC,EAAUtK,GAC1B,IAAM2M,EAAU,GAIhB,OAHAtY,EAASmY,EAAKlC,GAAU,SAAUjX,GAC9BsZ,EAAQ/R,KAAKvH,KACd2M,GACI2M,EAQX,SAAS7M,EAAMwK,GACX,OAAO0C,EAAOlN,MAAMwK,GAUxB,SAAS2C,EAAMT,EAAKlC,EAAUtK,GAC1B,OAAO8C,EAAM0J,EAAK1M,EAAMwK,GAAWtK,GAGvCiN,EAAMnN,MAAQA,EACdmN,EAAMnK,MAAQA,EACdmK,EAAM5Y,SAAWA,EACjB4Y,EAAMC,QAvPN,SAAiB7Z,EAAMiX,EAAUM,EAAU5K,GACvC,OAAKsK,KACAjX,IACAuX,IAAYA,EAAW,IAErBP,EAAWC,EAAXD,CAAqBhX,EAAMuX,EAAU5K,KAmPhDiN,EAAMA,MAAQA"} \ No newline at end of file diff --git a/node_modules/esquery/dist/esquery.js b/node_modules/esquery/dist/esquery.js new file mode 100644 index 0000000000000000000000000000000000000000..8f07f5b51081f224fe0892090590ebf8c7be5e3d --- /dev/null +++ b/node_modules/esquery/dist/esquery.js @@ -0,0 +1,4426 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.esquery = factory()); +}(this, (function () { 'use strict'; + + function _arrayLikeToArray(r, a) { + (null == a || a > r.length) && (a = r.length); + for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; + return n; + } + function _arrayWithHoles(r) { + if (Array.isArray(r)) return r; + } + function _arrayWithoutHoles(r) { + if (Array.isArray(r)) return _arrayLikeToArray(r); + } + function _iterableToArray(r) { + if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); + } + function _iterableToArrayLimit(r, l) { + var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; + if (null != t) { + var e, + n, + i, + u, + a = [], + f = !0, + o = !1; + try { + if (i = (t = t.call(r)).next, 0 === l) { + if (Object(t) !== t) return; + f = !1; + } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); + } catch (r) { + o = !0, n = r; + } finally { + try { + if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; + } finally { + if (o) throw n; + } + } + return a; + } + } + function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + function _slicedToArray(r, e) { + return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); + } + function _toConsumableArray(r) { + return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); + } + function _typeof(o) { + "@babel/helpers - typeof"; + + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { + return typeof o; + } : function (o) { + return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; + }, _typeof(o); + } + function _unsupportedIterableToArray(r, a) { + if (r) { + if ("string" == typeof r) return _arrayLikeToArray(r, a); + var t = {}.toString.call(r).slice(8, -1); + return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; + } + } + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + var estraverse = createCommonjsModule(function (module, exports) { + /* + Copyright (C) 2012-2013 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat + + 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. + + 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 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. + */ + /*jslint vars:false, bitwise:true*/ + /*jshint indent:4*/ + /*global exports:true*/ + (function clone(exports) { + + var Syntax, VisitorOption, VisitorKeys, BREAK, SKIP, REMOVE; + function deepCopy(obj) { + var ret = {}, + key, + val; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + val = obj[key]; + if (typeof val === 'object' && val !== null) { + ret[key] = deepCopy(val); + } else { + ret[key] = val; + } + } + } + return ret; + } + + // based on LLVM libc++ upper_bound / lower_bound + // MIT License + + function upperBound(array, func) { + var diff, len, i, current; + len = array.length; + i = 0; + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + len = diff; + } else { + i = current + 1; + len -= diff + 1; + } + } + return i; + } + Syntax = { + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AwaitExpression: 'AwaitExpression', + // CAUTION: It's deferred to ES7. + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ChainExpression: 'ChainExpression', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ComprehensionBlock: 'ComprehensionBlock', + // CAUTION: It's deferred to ES7. + ComprehensionExpression: 'ComprehensionExpression', + // CAUTION: It's deferred to ES7. + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DebuggerStatement: 'DebuggerStatement', + DirectiveStatement: 'DirectiveStatement', + DoWhileStatement: 'DoWhileStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + ForOfStatement: 'ForOfStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + GeneratorExpression: 'GeneratorExpression', + // CAUTION: It's deferred to ES7. + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportExpression: 'ImportExpression', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MetaProperty: 'MetaProperty', + MethodDefinition: 'MethodDefinition', + ModuleSpecifier: 'ModuleSpecifier', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + PrivateIdentifier: 'PrivateIdentifier', + Program: 'Program', + Property: 'Property', + PropertyDefinition: 'PropertyDefinition', + RestElement: 'RestElement', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + Super: 'Super', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; + VisitorKeys = { + AssignmentExpression: ['left', 'right'], + AssignmentPattern: ['left', 'right'], + ArrayExpression: ['elements'], + ArrayPattern: ['elements'], + ArrowFunctionExpression: ['params', 'body'], + AwaitExpression: ['argument'], + // CAUTION: It's deferred to ES7. + BlockStatement: ['body'], + BinaryExpression: ['left', 'right'], + BreakStatement: ['label'], + CallExpression: ['callee', 'arguments'], + CatchClause: ['param', 'body'], + ChainExpression: ['expression'], + ClassBody: ['body'], + ClassDeclaration: ['id', 'superClass', 'body'], + ClassExpression: ['id', 'superClass', 'body'], + ComprehensionBlock: ['left', 'right'], + // CAUTION: It's deferred to ES7. + ComprehensionExpression: ['blocks', 'filter', 'body'], + // CAUTION: It's deferred to ES7. + ConditionalExpression: ['test', 'consequent', 'alternate'], + ContinueStatement: ['label'], + DebuggerStatement: [], + DirectiveStatement: [], + DoWhileStatement: ['body', 'test'], + EmptyStatement: [], + ExportAllDeclaration: ['source'], + ExportDefaultDeclaration: ['declaration'], + ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], + ExportSpecifier: ['exported', 'local'], + ExpressionStatement: ['expression'], + ForStatement: ['init', 'test', 'update', 'body'], + ForInStatement: ['left', 'right', 'body'], + ForOfStatement: ['left', 'right', 'body'], + FunctionDeclaration: ['id', 'params', 'body'], + FunctionExpression: ['id', 'params', 'body'], + GeneratorExpression: ['blocks', 'filter', 'body'], + // CAUTION: It's deferred to ES7. + Identifier: [], + IfStatement: ['test', 'consequent', 'alternate'], + ImportExpression: ['source'], + ImportDeclaration: ['specifiers', 'source'], + ImportDefaultSpecifier: ['local'], + ImportNamespaceSpecifier: ['local'], + ImportSpecifier: ['imported', 'local'], + Literal: [], + LabeledStatement: ['label', 'body'], + LogicalExpression: ['left', 'right'], + MemberExpression: ['object', 'property'], + MetaProperty: ['meta', 'property'], + MethodDefinition: ['key', 'value'], + ModuleSpecifier: [], + NewExpression: ['callee', 'arguments'], + ObjectExpression: ['properties'], + ObjectPattern: ['properties'], + PrivateIdentifier: [], + Program: ['body'], + Property: ['key', 'value'], + PropertyDefinition: ['key', 'value'], + RestElement: ['argument'], + ReturnStatement: ['argument'], + SequenceExpression: ['expressions'], + SpreadElement: ['argument'], + Super: [], + SwitchStatement: ['discriminant', 'cases'], + SwitchCase: ['test', 'consequent'], + TaggedTemplateExpression: ['tag', 'quasi'], + TemplateElement: [], + TemplateLiteral: ['quasis', 'expressions'], + ThisExpression: [], + ThrowStatement: ['argument'], + TryStatement: ['block', 'handler', 'finalizer'], + UnaryExpression: ['argument'], + UpdateExpression: ['argument'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + WhileStatement: ['test', 'body'], + WithStatement: ['object', 'body'], + YieldExpression: ['argument'] + }; + + // unique id + BREAK = {}; + SKIP = {}; + REMOVE = {}; + VisitorOption = { + Break: BREAK, + Skip: SKIP, + Remove: REMOVE + }; + function Reference(parent, key) { + this.parent = parent; + this.key = key; + } + Reference.prototype.replace = function replace(node) { + this.parent[this.key] = node; + }; + Reference.prototype.remove = function remove() { + if (Array.isArray(this.parent)) { + this.parent.splice(this.key, 1); + return true; + } else { + this.replace(null); + return false; + } + }; + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } + function Controller() {} + + // API: + // return property path array from root to current node + Controller.prototype.path = function path() { + var i, iz, j, jz, result, element; + function addToPath(result, path) { + if (Array.isArray(path)) { + for (j = 0, jz = path.length; j < jz; ++j) { + result.push(path[j]); + } + } else { + result.push(path); + } + } + + // root node + if (!this.__current.path) { + return null; + } + + // first node is sentinel, second node is root element + result = []; + for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { + element = this.__leavelist[i]; + addToPath(result, element.path); + } + addToPath(result, this.__current.path); + return result; + }; + + // API: + // return type of current node + Controller.prototype.type = function () { + var node = this.current(); + return node.type || this.__current.wrap; + }; + + // API: + // return array of parent elements + Controller.prototype.parents = function parents() { + var i, iz, result; + + // first node is sentinel + result = []; + for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { + result.push(this.__leavelist[i].node); + } + return result; + }; + + // API: + // return current node + Controller.prototype.current = function current() { + return this.__current.node; + }; + Controller.prototype.__execute = function __execute(callback, element) { + var previous, result; + result = undefined; + previous = this.__current; + this.__current = element; + this.__state = null; + if (callback) { + result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); + } + this.__current = previous; + return result; + }; + + // API: + // notify control skip / break + Controller.prototype.notify = function notify(flag) { + this.__state = flag; + }; + + // API: + // skip child nodes of current node + Controller.prototype.skip = function () { + this.notify(SKIP); + }; + + // API: + // break traversals + Controller.prototype['break'] = function () { + this.notify(BREAK); + }; + + // API: + // remove node + Controller.prototype.remove = function () { + this.notify(REMOVE); + }; + Controller.prototype.__initialize = function (root, visitor) { + this.visitor = visitor; + this.root = root; + this.__worklist = []; + this.__leavelist = []; + this.__current = null; + this.__state = null; + this.__fallback = null; + if (visitor.fallback === 'iteration') { + this.__fallback = Object.keys; + } else if (typeof visitor.fallback === 'function') { + this.__fallback = visitor.fallback; + } + this.__keys = VisitorKeys; + if (visitor.keys) { + this.__keys = Object.assign(Object.create(this.__keys), visitor.keys); + } + }; + function isNode(node) { + if (node == null) { + return false; + } + return typeof node === 'object' && typeof node.type === 'string'; + } + function isProperty(nodeType, key) { + return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; + } + function candidateExistsInLeaveList(leavelist, candidate) { + for (var i = leavelist.length - 1; i >= 0; --i) { + if (leavelist[i].node === candidate) { + return true; + } + } + return false; + } + Controller.prototype.traverse = function traverse(root, visitor) { + var worklist, leavelist, element, node, nodeType, ret, key, current, current2, candidates, candidate, sentinel; + this.__initialize(root, visitor); + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + worklist.push(new Element(root, null, null, null)); + leavelist.push(new Element(null, null, null, null)); + while (worklist.length) { + element = worklist.pop(); + if (element === sentinel) { + element = leavelist.pop(); + ret = this.__execute(visitor.leave, element); + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } + if (element.node) { + ret = this.__execute(visitor.enter, element); + if (this.__state === BREAK || ret === BREAK) { + return; + } + worklist.push(sentinel); + leavelist.push(element); + if (this.__state === SKIP || ret === SKIP) { + continue; + } + node = element.node; + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (candidateExistsInLeaveList(leavelist, candidate[current2])) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', null); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, null); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + if (candidateExistsInLeaveList(leavelist, candidate)) { + continue; + } + worklist.push(new Element(candidate, key, null, null)); + } + } + } + } + }; + Controller.prototype.replace = function replace(root, visitor) { + var worklist, leavelist, node, nodeType, target, element, current, current2, candidates, candidate, sentinel, outer, key; + function removeElem(element) { + var i, key, nextElem, parent; + if (element.ref.remove()) { + // When the reference is an element of an array. + key = element.ref.key; + parent = element.ref.parent; + + // If removed from array, then decrease following items' keys. + i = worklist.length; + while (i--) { + nextElem = worklist[i]; + if (nextElem.ref && nextElem.ref.parent === parent) { + if (nextElem.ref.key < key) { + break; + } + --nextElem.ref.key; + } + } + } + } + this.__initialize(root, visitor); + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + outer = { + root: root + }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); + while (worklist.length) { + element = worklist.pop(); + if (element === sentinel) { + element = leavelist.pop(); + target = this.__execute(visitor.leave, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + } + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + } + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + continue; + } + target = this.__execute(visitor.enter, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + element.node = target; + } + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + element.node = null; + } + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + + // node may be null + node = element.node; + if (!node) { + continue; + } + worklist.push(sentinel); + leavelist.push(element); + if (this.__state === SKIP || target === SKIP) { + continue; + } + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, new Reference(node, key))); + } + } + } + return outer.root; + }; + function traverse(root, visitor) { + var controller = new Controller(); + return controller.traverse(root, visitor); + } + function replace(root, visitor) { + var controller = new Controller(); + return controller.replace(root, visitor); + } + function extendCommentRange(comment, tokens) { + var target; + target = upperBound(tokens, function search(token) { + return token.range[0] > comment.range[0]; + }); + comment.extendedRange = [comment.range[0], comment.range[1]]; + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } + return comment; + } + function attachComments(tree, providedComments, tokens) { + // At first, we should calculate extended comment ranges. + var comments = [], + comment, + len, + i, + cursor; + if (!tree.range) { + throw new Error('attachComments needs range information'); + } + + // tokens array is empty, we attach comments to tree as 'leadingComments' + if (!tokens.length) { + if (providedComments.length) { + for (i = 0, len = providedComments.length; i < len; i += 1) { + comment = deepCopy(providedComments[i]); + comment.extendedRange = [0, tree.range[0]]; + comments.push(comment); + } + tree.leadingComments = comments; + } + return tree; + } + for (i = 0, len = providedComments.length; i < len; i += 1) { + comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); + } + + // This is based on John Freeman's implementation. + cursor = 0; + traverse(tree, { + enter: function (node) { + var comment; + while (cursor < comments.length) { + comment = comments[cursor]; + if (comment.extendedRange[1] > node.range[0]) { + break; + } + if (comment.extendedRange[1] === node.range[0]) { + if (!node.leadingComments) { + node.leadingComments = []; + } + node.leadingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + cursor = 0; + traverse(tree, { + leave: function (node) { + var comment; + while (cursor < comments.length) { + comment = comments[cursor]; + if (node.range[1] < comment.extendedRange[0]) { + break; + } + if (node.range[1] === comment.extendedRange[0]) { + if (!node.trailingComments) { + node.trailingComments = []; + } + node.trailingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + return tree; + } + exports.Syntax = Syntax; + exports.traverse = traverse; + exports.replace = replace; + exports.attachComments = attachComments; + exports.VisitorKeys = VisitorKeys; + exports.VisitorOption = VisitorOption; + exports.Controller = Controller; + exports.cloneEnvironment = function () { + return clone({}); + }; + return exports; + })(exports); + /* vim: set sw=4 ts=4 et tw=80 : */ + }); + + var parser = createCommonjsModule(function (module) { + /* + * Generated by PEG.js 0.10.0. + * + * http://pegjs.org/ + */ + (function (root, factory) { + if ( module.exports) { + module.exports = factory(); + } + })(commonjsGlobal, function () { + + function peg$subclass(child, parent) { + function ctor() { + this.constructor = child; + } + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + } + function peg$SyntaxError(message, expected, found, location) { + this.message = message; + this.expected = expected; + this.found = found; + this.location = location; + this.name = "SyntaxError"; + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, peg$SyntaxError); + } + } + peg$subclass(peg$SyntaxError, Error); + peg$SyntaxError.buildMessage = function (expected, found) { + var DESCRIBE_EXPECTATION_FNS = { + literal: function literal(expectation) { + return "\"" + literalEscape(expectation.text) + "\""; + }, + "class": function _class(expectation) { + var escapedParts = "", + i; + for (i = 0; i < expectation.parts.length; i++) { + escapedParts += expectation.parts[i] instanceof Array ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) : classEscape(expectation.parts[i]); + } + return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; + }, + any: function any(expectation) { + return "any character"; + }, + end: function end(expectation) { + return "end of input"; + }, + other: function other(expectation) { + return expectation.description; + } + }; + function hex(ch) { + return ch.charCodeAt(0).toString(16).toUpperCase(); + } + function literalEscape(s) { + return s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\0/g, '\\0').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/[\x00-\x0F]/g, function (ch) { + return '\\x0' + hex(ch); + }).replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { + return '\\x' + hex(ch); + }); + } + function classEscape(s) { + return s.replace(/\\/g, '\\\\').replace(/\]/g, '\\]').replace(/\^/g, '\\^').replace(/-/g, '\\-').replace(/\0/g, '\\0').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/[\x00-\x0F]/g, function (ch) { + return '\\x0' + hex(ch); + }).replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { + return '\\x' + hex(ch); + }); + } + function describeExpectation(expectation) { + return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); + } + function describeExpected(expected) { + var descriptions = new Array(expected.length), + i, + j; + for (i = 0; i < expected.length; i++) { + descriptions[i] = describeExpectation(expected[i]); + } + descriptions.sort(); + if (descriptions.length > 0) { + for (i = 1, j = 1; i < descriptions.length; i++) { + if (descriptions[i - 1] !== descriptions[i]) { + descriptions[j] = descriptions[i]; + j++; + } + } + descriptions.length = j; + } + switch (descriptions.length) { + case 1: + return descriptions[0]; + case 2: + return descriptions[0] + " or " + descriptions[1]; + default: + return descriptions.slice(0, -1).join(", ") + ", or " + descriptions[descriptions.length - 1]; + } + } + function describeFound(found) { + return found ? "\"" + literalEscape(found) + "\"" : "end of input"; + } + return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; + }; + function peg$parse(input, options) { + options = options !== void 0 ? options : {}; + var peg$FAILED = {}, + peg$startRuleFunctions = { + start: peg$parsestart + }, + peg$startRuleFunction = peg$parsestart, + peg$c0 = function peg$c0(ss) { + return ss.length === 1 ? ss[0] : { + type: 'matches', + selectors: ss + }; + }, + peg$c1 = function peg$c1() { + return void 0; + }, + peg$c2 = " ", + peg$c3 = peg$literalExpectation(" ", false), + peg$c4 = /^[^ [\],():#!=><~+.]/, + peg$c5 = peg$classExpectation([" ", "[", "]", ",", "(", ")", ":", "#", "!", "=", ">", "<", "~", "+", "."], true, false), + peg$c6 = function peg$c6(i) { + return i.join(''); + }, + peg$c7 = ">", + peg$c8 = peg$literalExpectation(">", false), + peg$c9 = function peg$c9() { + return 'child'; + }, + peg$c10 = "~", + peg$c11 = peg$literalExpectation("~", false), + peg$c12 = function peg$c12() { + return 'sibling'; + }, + peg$c13 = "+", + peg$c14 = peg$literalExpectation("+", false), + peg$c15 = function peg$c15() { + return 'adjacent'; + }, + peg$c16 = function peg$c16() { + return 'descendant'; + }, + peg$c17 = ",", + peg$c18 = peg$literalExpectation(",", false), + peg$c19 = function peg$c19(s, ss) { + return [s].concat(ss.map(function (s) { + return s[3]; + })); + }, + peg$c20 = function peg$c20(op, s) { + if (!op) return s; + return { + type: op, + left: { + type: 'exactNode' + }, + right: s + }; + }, + peg$c21 = function peg$c21(a, ops) { + return ops.reduce(function (memo, rhs) { + return { + type: rhs[0], + left: memo, + right: rhs[1] + }; + }, a); + }, + peg$c22 = "!", + peg$c23 = peg$literalExpectation("!", false), + peg$c24 = function peg$c24(subject, as) { + var b = as.length === 1 ? as[0] : { + type: 'compound', + selectors: as + }; + if (subject) b.subject = true; + return b; + }, + peg$c25 = "*", + peg$c26 = peg$literalExpectation("*", false), + peg$c27 = function peg$c27(a) { + return { + type: 'wildcard', + value: a + }; + }, + peg$c28 = "#", + peg$c29 = peg$literalExpectation("#", false), + peg$c30 = function peg$c30(i) { + return { + type: 'identifier', + value: i + }; + }, + peg$c31 = "[", + peg$c32 = peg$literalExpectation("[", false), + peg$c33 = "]", + peg$c34 = peg$literalExpectation("]", false), + peg$c35 = function peg$c35(v) { + return v; + }, + peg$c36 = /^[>", "<", "!"], false, false), + peg$c38 = "=", + peg$c39 = peg$literalExpectation("=", false), + peg$c40 = function peg$c40(a) { + return (a || '') + '='; + }, + peg$c41 = /^[><]/, + peg$c42 = peg$classExpectation([">", "<"], false, false), + peg$c43 = ".", + peg$c44 = peg$literalExpectation(".", false), + peg$c45 = function peg$c45(a, as) { + return [].concat.apply([a], as).join(''); + }, + peg$c46 = function peg$c46(name, op, value) { + return { + type: 'attribute', + name: name, + operator: op, + value: value + }; + }, + peg$c47 = function peg$c47(name) { + return { + type: 'attribute', + name: name + }; + }, + peg$c48 = "\"", + peg$c49 = peg$literalExpectation("\"", false), + peg$c50 = /^[^\\"]/, + peg$c51 = peg$classExpectation(["\\", "\""], true, false), + peg$c52 = "\\", + peg$c53 = peg$literalExpectation("\\", false), + peg$c54 = peg$anyExpectation(), + peg$c55 = function peg$c55(a, b) { + return a + b; + }, + peg$c56 = function peg$c56(d) { + return { + type: 'literal', + value: strUnescape(d.join('')) + }; + }, + peg$c57 = "'", + peg$c58 = peg$literalExpectation("'", false), + peg$c59 = /^[^\\']/, + peg$c60 = peg$classExpectation(["\\", "'"], true, false), + peg$c61 = /^[0-9]/, + peg$c62 = peg$classExpectation([["0", "9"]], false, false), + peg$c63 = function peg$c63(a, b) { + // Can use `a.flat().join('')` once supported + var leadingDecimals = a ? [].concat.apply([], a).join('') : ''; + return { + type: 'literal', + value: parseFloat(leadingDecimals + b.join('')) + }; + }, + peg$c64 = function peg$c64(i) { + return { + type: 'literal', + value: i + }; + }, + peg$c65 = "type(", + peg$c66 = peg$literalExpectation("type(", false), + peg$c67 = /^[^ )]/, + peg$c68 = peg$classExpectation([" ", ")"], true, false), + peg$c69 = ")", + peg$c70 = peg$literalExpectation(")", false), + peg$c71 = function peg$c71(t) { + return { + type: 'type', + value: t.join('') + }; + }, + peg$c72 = /^[imsu]/, + peg$c73 = peg$classExpectation(["i", "m", "s", "u"], false, false), + peg$c74 = "/", + peg$c75 = peg$literalExpectation("/", false), + peg$c76 = function peg$c76(pattern, flgs) { + return { + type: 'regexp', + value: new RegExp(pattern.join(''), flgs ? flgs.join('') : '') + }; + }, + peg$c77 = /^[^\]\\]/, + peg$c78 = peg$classExpectation(["]", "\\"], true, false), + peg$c79 = function peg$c79(cs) { + return '[' + cs.join('') + ']'; + }, + peg$c80 = function peg$c80(a) { + return '\\' + a; + }, + peg$c81 = /^[^\/\\[]/, + peg$c82 = peg$classExpectation(["/", "\\", "["], true, false), + peg$c83 = function peg$c83(cs) { + return cs.join(''); + }, + peg$c84 = function peg$c84(i, is) { + return { + type: 'field', + name: is.reduce(function (memo, p) { + return memo + p[0] + p[1]; + }, i) + }; + }, + peg$c85 = ":not(", + peg$c86 = peg$literalExpectation(":not(", false), + peg$c87 = function peg$c87(ss) { + return { + type: 'not', + selectors: ss + }; + }, + peg$c88 = ":matches(", + peg$c89 = peg$literalExpectation(":matches(", false), + peg$c90 = function peg$c90(ss) { + return { + type: 'matches', + selectors: ss + }; + }, + peg$c91 = ":is(", + peg$c92 = peg$literalExpectation(":is(", false), + peg$c93 = ":has(", + peg$c94 = peg$literalExpectation(":has(", false), + peg$c95 = function peg$c95(ss) { + return { + type: 'has', + selectors: ss + }; + }, + peg$c96 = ":first-child", + peg$c97 = peg$literalExpectation(":first-child", false), + peg$c98 = function peg$c98() { + return nth(1); + }, + peg$c99 = ":last-child", + peg$c100 = peg$literalExpectation(":last-child", false), + peg$c101 = function peg$c101() { + return nthLast(1); + }, + peg$c102 = ":nth-child(", + peg$c103 = peg$literalExpectation(":nth-child(", false), + peg$c104 = function peg$c104(n) { + return nth(parseInt(n.join(''), 10)); + }, + peg$c105 = ":nth-last-child(", + peg$c106 = peg$literalExpectation(":nth-last-child(", false), + peg$c107 = function peg$c107(n) { + return nthLast(parseInt(n.join(''), 10)); + }, + peg$c108 = ":", + peg$c109 = peg$literalExpectation(":", false), + peg$c110 = function peg$c110(c) { + return { + type: 'class', + name: c + }; + }, + peg$currPos = 0, + peg$posDetailsCache = [{ + line: 1, + column: 1 + }], + peg$maxFailPos = 0, + peg$maxFailExpected = [], + peg$resultsCache = {}, + peg$result; + if ("startRule" in options) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); + } + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + function peg$literalExpectation(text, ignoreCase) { + return { + type: "literal", + text: text, + ignoreCase: ignoreCase + }; + } + function peg$classExpectation(parts, inverted, ignoreCase) { + return { + type: "class", + parts: parts, + inverted: inverted, + ignoreCase: ignoreCase + }; + } + function peg$anyExpectation() { + return { + type: "any" + }; + } + function peg$endExpectation() { + return { + type: "end" + }; + } + function peg$computePosDetails(pos) { + var details = peg$posDetailsCache[pos], + p; + if (details) { + return details; + } else { + p = pos - 1; + while (!peg$posDetailsCache[p]) { + p--; + } + details = peg$posDetailsCache[p]; + details = { + line: details.line, + column: details.column + }; + while (p < pos) { + if (input.charCodeAt(p) === 10) { + details.line++; + details.column = 1; + } else { + details.column++; + } + p++; + } + peg$posDetailsCache[pos] = details; + return details; + } + } + function peg$computeLocation(startPos, endPos) { + var startPosDetails = peg$computePosDetails(startPos), + endPosDetails = peg$computePosDetails(endPos); + return { + start: { + offset: startPos, + line: startPosDetails.line, + column: startPosDetails.column + }, + end: { + offset: endPos, + line: endPosDetails.line, + column: endPosDetails.column + } + }; + } + function peg$fail(expected) { + if (peg$currPos < peg$maxFailPos) { + return; + } + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; + } + peg$maxFailExpected.push(expected); + } + function peg$buildStructuredError(expected, found, location) { + return new peg$SyntaxError(peg$SyntaxError.buildMessage(expected, found), expected, found, location); + } + function peg$parsestart() { + var s0, s1, s2, s3; + var key = peg$currPos * 36 + 0, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + s2 = peg$parseselectors(); + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c0(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + s1 = peg$c1(); + } + s0 = s1; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parse_() { + var s0, s1; + var key = peg$currPos * 36 + 1, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = []; + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c3); + } + } + while (s1 !== peg$FAILED) { + s0.push(s1); + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c3); + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseidentifierName() { + var s0, s1, s2; + var key = peg$currPos * 36 + 2, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = []; + if (peg$c4.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c5); + } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + if (peg$c4.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c5); + } + } + } + } else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s1 = peg$c6(s1); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsebinaryOp() { + var s0, s1, s2, s3; + var key = peg$currPos * 36 + 3, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 62) { + s2 = peg$c7; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c8); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c9(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c10; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c11); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c12(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c13; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c14); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c15(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c3); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s1 = peg$c16(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsehasSelectors() { + var s0, s1, s2, s3, s4, s5, s6, s7; + var key = peg$currPos * 36 + 4, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parsehasSelector(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parsehasSelector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parsehasSelector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c19(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseselectors() { + var s0, s1, s2, s3, s4, s5, s6, s7; + var key = peg$currPos * 36 + 5, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseselector(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseselector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseselector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c19(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsehasSelector() { + var s0, s1, s2; + var key = peg$currPos * 36 + 6, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parsebinaryOp(); + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseselector(); + if (s2 !== peg$FAILED) { + s1 = peg$c20(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseselector() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 7, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parsesequence(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parsebinaryOp(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesequence(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parsebinaryOp(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesequence(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c21(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsesequence() { + var s0, s1, s2, s3; + var key = peg$currPos * 36 + 8, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 33) { + s1 = peg$c22; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c23); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseatom(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseatom(); + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = peg$c24(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseatom() { + var s0; + var key = peg$currPos * 36 + 9, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$parsewildcard(); + if (s0 === peg$FAILED) { + s0 = peg$parseidentifier(); + if (s0 === peg$FAILED) { + s0 = peg$parseattr(); + if (s0 === peg$FAILED) { + s0 = peg$parsefield(); + if (s0 === peg$FAILED) { + s0 = peg$parsenegation(); + if (s0 === peg$FAILED) { + s0 = peg$parsematches(); + if (s0 === peg$FAILED) { + s0 = peg$parseis(); + if (s0 === peg$FAILED) { + s0 = peg$parsehas(); + if (s0 === peg$FAILED) { + s0 = peg$parsefirstChild(); + if (s0 === peg$FAILED) { + s0 = peg$parselastChild(); + if (s0 === peg$FAILED) { + s0 = peg$parsenthChild(); + if (s0 === peg$FAILED) { + s0 = peg$parsenthLastChild(); + if (s0 === peg$FAILED) { + s0 = peg$parseclass(); + } + } + } + } + } + } + } + } + } + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsewildcard() { + var s0, s1; + var key = peg$currPos * 36 + 10, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 42) { + s1 = peg$c25; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c26); + } + } + if (s1 !== peg$FAILED) { + s1 = peg$c27(s1); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseidentifier() { + var s0, s1, s2; + var key = peg$currPos * 36 + 11, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 35) { + s1 = peg$c28; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c29); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + s1 = peg$c30(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattr() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 12, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c31; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c32); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrValue(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s5 = peg$c33; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c34); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c35(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrOps() { + var s0, s1, s2; + var key = peg$currPos * 36 + 13, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (peg$c36.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c37); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c39); + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c40(s1); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + if (peg$c41.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + { + peg$fail(peg$c42); + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrEqOps() { + var s0, s1, s2; + var key = peg$currPos * 36 + 14, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 33) { + s1 = peg$c22; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c23); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c39); + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c40(s1); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrName() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 15, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseidentifierName(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c43; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseidentifierName(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c43; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseidentifierName(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c45(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrValue() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 16, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrEqOps(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetype(); + if (s5 === peg$FAILED) { + s5 = peg$parseregex(); + } + if (s5 !== peg$FAILED) { + s1 = peg$c46(s1, s3, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrOps(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + s5 = peg$parsestring(); + if (s5 === peg$FAILED) { + s5 = peg$parsenumber(); + if (s5 === peg$FAILED) { + s5 = peg$parsepath(); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c46(s1, s3, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s1 = peg$c47(s1); + } + s0 = s1; + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsestring() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 17, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 34) { + s1 = peg$c48; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c49); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c50.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c51); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c50.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c51); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 34) { + s3 = peg$c48; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c49); + } + } + if (s3 !== peg$FAILED) { + s1 = peg$c56(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 39) { + s1 = peg$c57; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c58); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c59.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c60); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c59.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c60); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s3 = peg$c57; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c58); + } + } + if (s3 !== peg$FAILED) { + s1 = peg$c56(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenumber() { + var s0, s1, s2, s3; + var key = peg$currPos * 36 + 18, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$currPos; + s2 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s3 = peg$c43; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = peg$c63(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsepath() { + var s0, s1; + var key = peg$currPos * 36 + 19, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseidentifierName(); + if (s1 !== peg$FAILED) { + s1 = peg$c64(s1); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsetype() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 20, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c65) { + s1 = peg$c65; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c66); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c67.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c68); + } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c67.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c68); + } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c71(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseflags() { + var s0, s1; + var key = peg$currPos * 36 + 21, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = []; + if (peg$c72.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c73); + } + } + if (s1 !== peg$FAILED) { + while (s1 !== peg$FAILED) { + s0.push(s1); + if (peg$c72.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c73); + } + } + } + } else { + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseregex() { + var s0, s1, s2, s3, s4; + var key = peg$currPos * 36 + 22, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 47) { + s1 = peg$c74; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c75); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsere_character_class(); + if (s3 === peg$FAILED) { + s3 = peg$parsere_escape(); + if (s3 === peg$FAILED) { + s3 = peg$parsere_chars(); + } + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsere_character_class(); + if (s3 === peg$FAILED) { + s3 = peg$parsere_escape(); + if (s3 === peg$FAILED) { + s3 = peg$parsere_chars(); + } + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s3 = peg$c74; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c75); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseflags(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s1 = peg$c76(s2, s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsere_character_class() { + var s0, s1, s2, s3; + var key = peg$currPos * 36 + 23, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c31; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c32); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c77.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c78); + } + } + if (s3 === peg$FAILED) { + s3 = peg$parsere_escape(); + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c77.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c78); + } + } + if (s3 === peg$FAILED) { + s3 = peg$parsere_escape(); + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c33; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c34); + } + } + if (s3 !== peg$FAILED) { + s1 = peg$c79(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsere_escape() { + var s0, s1, s2; + var key = peg$currPos * 36 + 24, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s1 = peg$c52; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c80(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsere_chars() { + var s0, s1, s2; + var key = peg$currPos * 36 + 25, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = []; + if (peg$c81.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c82); + } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + if (peg$c81.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c82); + } + } + } + } else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s1 = peg$c83(s1); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsefield() { + var s0, s1, s2, s3, s4, s5, s6; + var key = peg$currPos * 36 + 26, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c43; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c43; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseidentifierName(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c43; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseidentifierName(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s1 = peg$c84(s2, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenegation() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 27, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c85) { + s1 = peg$c85; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c86); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c87(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsematches() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 28, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 9) === peg$c88) { + s1 = peg$c88; + peg$currPos += 9; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c89); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c90(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseis() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 29, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 4) === peg$c91) { + s1 = peg$c91; + peg$currPos += 4; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c92); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c90(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsehas() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 30, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c93) { + s1 = peg$c93; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c94); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parsehasSelectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c95(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsefirstChild() { + var s0, s1; + var key = peg$currPos * 36 + 31, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 12) === peg$c96) { + s1 = peg$c96; + peg$currPos += 12; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c97); + } + } + if (s1 !== peg$FAILED) { + s1 = peg$c98(); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parselastChild() { + var s0, s1; + var key = peg$currPos * 36 + 32, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c99) { + s1 = peg$c99; + peg$currPos += 11; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c100); + } + } + if (s1 !== peg$FAILED) { + s1 = peg$c101(); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenthChild() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 33, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c102) { + s1 = peg$c102; + peg$currPos += 11; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c103); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c104(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenthLastChild() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 34, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 16) === peg$c105) { + s1 = peg$c105; + peg$currPos += 16; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c106); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c107(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseclass() { + var s0, s1, s2; + var key = peg$currPos * 36 + 35, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s1 = peg$c108; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c109); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + s1 = peg$c110(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function nth(n) { + return { + type: 'nth-child', + index: { + type: 'literal', + value: n + } + }; + } + function nthLast(n) { + return { + type: 'nth-last-child', + index: { + type: 'literal', + value: n + } + }; + } + function strUnescape(s) { + return s.replace(/\\(.)/g, function (match, ch) { + switch (ch) { + case 'b': + return '\b'; + case 'f': + return '\f'; + case 'n': + return '\n'; + case 'r': + return '\r'; + case 't': + return '\t'; + case 'v': + return '\v'; + default: + return ch; + } + }); + } + peg$result = peg$startRuleFunction(); + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail(peg$endExpectation()); + } + throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)); + } + } + return { + SyntaxError: peg$SyntaxError, + parse: peg$parse + }; + }); + }); + + /** + * @typedef {"LEFT_SIDE"|"RIGHT_SIDE"} Side + */ + + var LEFT_SIDE = 'LEFT_SIDE'; + var RIGHT_SIDE = 'RIGHT_SIDE'; + + /** + * @external AST + * @see https://esprima.readthedocs.io/en/latest/syntax-tree-format.html + */ + + /** + * One of the rules of `grammar.pegjs` + * @typedef {PlainObject} SelectorAST + * @see grammar.pegjs + */ + + /** + * The `sequence` production of `grammar.pegjs` + * @typedef {PlainObject} SelectorSequenceAST + */ + + /** + * Get the value of a property which may be multiple levels down + * in the object. + * @param {?PlainObject} obj + * @param {string[]} keys + * @returns {undefined|boolean|string|number|external:AST} + */ + function getPath(obj, keys) { + for (var i = 0; i < keys.length; ++i) { + if (obj == null) { + return obj; + } + obj = obj[keys[i]]; + } + return obj; + } + + /** + * Determine whether `node` can be reached by following `path`, + * starting at `ancestor`. + * @param {?external:AST} node + * @param {?external:AST} ancestor + * @param {string[]} path + * @param {Integer} fromPathIndex + * @returns {boolean} + */ + function inPath(node, ancestor, path, fromPathIndex) { + var current = ancestor; + for (var i = fromPathIndex; i < path.length; ++i) { + if (current == null) { + return false; + } + var field = current[path[i]]; + if (Array.isArray(field)) { + for (var k = 0; k < field.length; ++k) { + if (inPath(node, field[k], path, i + 1)) { + return true; + } + } + return false; + } + current = field; + } + return node === current; + } + + /** + * A generated matcher function for a selector. + * @callback SelectorMatcher + * @param {?SelectorAST} selector + * @param {external:AST[]} [ancestry=[]] + * @param {ESQueryOptions} [options] + * @returns {void} + */ + + /** + * A WeakMap for holding cached matcher functions for selectors. + * @type {WeakMap} + */ + var MATCHER_CACHE = typeof WeakMap === 'function' ? new WeakMap() : null; + + /** + * Look up a matcher function for `selector` in the cache. + * If it does not exist, generate it with `generateMatcher` and add it to the cache. + * In engines without WeakMap, the caching is skipped and matchers are generated with every call. + * @param {?SelectorAST} selector + * @returns {SelectorMatcher} + */ + function getMatcher(selector) { + if (selector == null) { + return function () { + return true; + }; + } + if (MATCHER_CACHE != null) { + var matcher = MATCHER_CACHE.get(selector); + if (matcher != null) { + return matcher; + } + matcher = generateMatcher(selector); + MATCHER_CACHE.set(selector, matcher); + return matcher; + } + return generateMatcher(selector); + } + + /** + * Create a matcher function for `selector`, + * @param {?SelectorAST} selector + * @returns {SelectorMatcher} + */ + function generateMatcher(selector) { + switch (selector.type) { + case 'wildcard': + return function () { + return true; + }; + case 'identifier': + { + var value = selector.value.toLowerCase(); + return function (node, ancestry, options) { + var nodeTypeKey = options && options.nodeTypeKey || 'type'; + return value === node[nodeTypeKey].toLowerCase(); + }; + } + case 'exactNode': + return function (node, ancestry) { + return ancestry.length === 0; + }; + case 'field': + { + var path = selector.name.split('.'); + return function (node, ancestry) { + var ancestor = ancestry[path.length - 1]; + return inPath(node, ancestor, path, 0); + }; + } + case 'matches': + { + var matchers = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + for (var i = 0; i < matchers.length; ++i) { + if (matchers[i](node, ancestry, options)) { + return true; + } + } + return false; + }; + } + case 'compound': + { + var _matchers = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + for (var i = 0; i < _matchers.length; ++i) { + if (!_matchers[i](node, ancestry, options)) { + return false; + } + } + return true; + }; + } + case 'not': + { + var _matchers2 = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + for (var i = 0; i < _matchers2.length; ++i) { + if (_matchers2[i](node, ancestry, options)) { + return false; + } + } + return true; + }; + } + case 'has': + { + var _matchers3 = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + var result = false; + var a = []; + estraverse.traverse(node, { + enter: function enter(node, parent) { + if (parent != null) { + a.unshift(parent); + } + for (var i = 0; i < _matchers3.length; ++i) { + if (_matchers3[i](node, a, options)) { + result = true; + this["break"](); + return; + } + } + }, + leave: function leave() { + a.shift(); + }, + keys: options && options.visitorKeys, + fallback: options && options.fallback || 'iteration' + }); + return result; + }; + } + case 'child': + { + var left = getMatcher(selector.left); + var right = getMatcher(selector.right); + return function (node, ancestry, options) { + if (ancestry.length > 0 && right(node, ancestry, options)) { + return left(ancestry[0], ancestry.slice(1), options); + } + return false; + }; + } + case 'descendant': + { + var _left = getMatcher(selector.left); + var _right = getMatcher(selector.right); + return function (node, ancestry, options) { + if (_right(node, ancestry, options)) { + for (var i = 0, l = ancestry.length; i < l; ++i) { + if (_left(ancestry[i], ancestry.slice(i + 1), options)) { + return true; + } + } + } + return false; + }; + } + case 'attribute': + { + var _path = selector.name.split('.'); + switch (selector.operator) { + case void 0: + return function (node) { + return getPath(node, _path) != null; + }; + case '=': + switch (selector.value.type) { + case 'regexp': + return function (node) { + var p = getPath(node, _path); + return typeof p === 'string' && selector.value.value.test(p); + }; + case 'literal': + { + var literal = "".concat(selector.value.value); + return function (node) { + return literal === "".concat(getPath(node, _path)); + }; + } + case 'type': + return function (node) { + return selector.value.value === _typeof(getPath(node, _path)); + }; + } + throw new Error("Unknown selector value type: ".concat(selector.value.type)); + case '!=': + switch (selector.value.type) { + case 'regexp': + return function (node) { + return !selector.value.value.test(getPath(node, _path)); + }; + case 'literal': + { + var _literal = "".concat(selector.value.value); + return function (node) { + return _literal !== "".concat(getPath(node, _path)); + }; + } + case 'type': + return function (node) { + return selector.value.value !== _typeof(getPath(node, _path)); + }; + } + throw new Error("Unknown selector value type: ".concat(selector.value.type)); + case '<=': + return function (node) { + return getPath(node, _path) <= selector.value.value; + }; + case '<': + return function (node) { + return getPath(node, _path) < selector.value.value; + }; + case '>': + return function (node) { + return getPath(node, _path) > selector.value.value; + }; + case '>=': + return function (node) { + return getPath(node, _path) >= selector.value.value; + }; + } + throw new Error("Unknown operator: ".concat(selector.operator)); + } + case 'sibling': + { + var _left2 = getMatcher(selector.left); + var _right2 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right2(node, ancestry, options) && sibling(node, _left2, ancestry, LEFT_SIDE, options) || selector.left.subject && _left2(node, ancestry, options) && sibling(node, _right2, ancestry, RIGHT_SIDE, options); + }; + } + case 'adjacent': + { + var _left3 = getMatcher(selector.left); + var _right3 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right3(node, ancestry, options) && adjacent(node, _left3, ancestry, LEFT_SIDE, options) || selector.right.subject && _left3(node, ancestry, options) && adjacent(node, _right3, ancestry, RIGHT_SIDE, options); + }; + } + case 'nth-child': + { + var nth = selector.index.value; + var _right4 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right4(node, ancestry, options) && nthChild(node, ancestry, nth, options); + }; + } + case 'nth-last-child': + { + var _nth = -selector.index.value; + var _right5 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right5(node, ancestry, options) && nthChild(node, ancestry, _nth, options); + }; + } + case 'class': + { + var name = selector.name.toLowerCase(); + return function (node, ancestry, options) { + if (options && options.matchClass) { + return options.matchClass(selector.name, node, ancestry); + } + if (options && options.nodeTypeKey) return false; + switch (name) { + case 'statement': + if (node.type.slice(-9) === 'Statement') return true; + // fallthrough: interface Declaration <: Statement { } + case 'declaration': + return node.type.slice(-11) === 'Declaration'; + case 'pattern': + if (node.type.slice(-7) === 'Pattern') return true; + // fallthrough: interface Expression <: Node, Pattern { } + case 'expression': + return node.type.slice(-10) === 'Expression' || node.type.slice(-7) === 'Literal' || node.type === 'Identifier' && (ancestry.length === 0 || ancestry[0].type !== 'MetaProperty') || node.type === 'MetaProperty'; + case 'function': + return node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression'; + } + throw new Error("Unknown class name: ".concat(selector.name)); + }; + } + } + throw new Error("Unknown selector type: ".concat(selector.type)); + } + + /** + * @callback TraverseOptionFallback + * @param {external:AST} node The given node. + * @returns {string[]} An array of visitor keys for the given node. + */ + + /** + * @callback ClassMatcher + * @param {string} className The name of the class to match. + * @param {external:AST} node The node to match against. + * @param {Array} ancestry The ancestry of the node. + * @returns {boolean} True if the node matches the class, false if not. + */ + + /** + * @typedef {object} ESQueryOptions + * @property {string} [nodeTypeKey="type"] By passing `nodeTypeKey`, we can allow other ASTs to use ESQuery. + * @property { { [nodeType: string]: string[] } } [visitorKeys] By passing `visitorKeys` mapping, we can extend the properties of the nodes that traverse the node. + * @property {TraverseOptionFallback} [fallback] By passing `fallback` option, we can control the properties of traversing nodes when encountering unknown nodes. + * @property {ClassMatcher} [matchClass] By passing `matchClass` option, we can customize the interpretation of classes. + */ + + /** + * Given a `node` and its ancestors, determine if `node` is matched + * by `selector`. + * @param {?external:AST} node + * @param {?SelectorAST} selector + * @param {external:AST[]} [ancestry=[]] + * @param {ESQueryOptions} [options] + * @throws {Error} Unknowns (operator, class name, selector type, or + * selector value type) + * @returns {boolean} + */ + function matches(node, selector, ancestry, options) { + if (!selector) { + return true; + } + if (!node) { + return false; + } + if (!ancestry) { + ancestry = []; + } + return getMatcher(selector)(node, ancestry, options); + } + + /** + * Get visitor keys of a given node. + * @param {external:AST} node The AST node to get keys. + * @param {ESQueryOptions|undefined} options + * @returns {string[]} Visitor keys of the node. + */ + function getVisitorKeys(node, options) { + var nodeTypeKey = options && options.nodeTypeKey || 'type'; + var nodeType = node[nodeTypeKey]; + if (options && options.visitorKeys && options.visitorKeys[nodeType]) { + return options.visitorKeys[nodeType]; + } + if (estraverse.VisitorKeys[nodeType]) { + return estraverse.VisitorKeys[nodeType]; + } + if (options && typeof options.fallback === 'function') { + return options.fallback(node); + } + // 'iteration' fallback + return Object.keys(node).filter(function (key) { + return key !== nodeTypeKey; + }); + } + + /** + * Check whether the given value is an ASTNode or not. + * @param {any} node The value to check. + * @param {ESQueryOptions|undefined} options The options to use. + * @returns {boolean} `true` if the value is an ASTNode. + */ + function isNode(node, options) { + var nodeTypeKey = options && options.nodeTypeKey || 'type'; + return node !== null && _typeof(node) === 'object' && typeof node[nodeTypeKey] === 'string'; + } + + /** + * Determines if the given node has a sibling that matches the + * given selector matcher. + * @param {external:AST} node + * @param {SelectorMatcher} matcher + * @param {external:AST[]} ancestry + * @param {Side} side + * @param {ESQueryOptions|undefined} options + * @returns {boolean} + */ + function sibling(node, matcher, ancestry, side, options) { + var _ancestry = _slicedToArray(ancestry, 1), + parent = _ancestry[0]; + if (!parent) { + return false; + } + var keys = getVisitorKeys(parent, options); + for (var i = 0; i < keys.length; ++i) { + var listProp = parent[keys[i]]; + if (Array.isArray(listProp)) { + var startIndex = listProp.indexOf(node); + if (startIndex < 0) { + continue; + } + var lowerBound = void 0, + upperBound = void 0; + if (side === LEFT_SIDE) { + lowerBound = 0; + upperBound = startIndex; + } else { + lowerBound = startIndex + 1; + upperBound = listProp.length; + } + for (var k = lowerBound; k < upperBound; ++k) { + if (isNode(listProp[k], options) && matcher(listProp[k], ancestry, options)) { + return true; + } + } + } + } + return false; + } + + /** + * Determines if the given node has an adjacent sibling that matches + * the given selector matcher. + * @param {external:AST} node + * @param {SelectorMatcher} matcher + * @param {external:AST[]} ancestry + * @param {Side} side + * @param {ESQueryOptions|undefined} options + * @returns {boolean} + */ + function adjacent(node, matcher, ancestry, side, options) { + var _ancestry2 = _slicedToArray(ancestry, 1), + parent = _ancestry2[0]; + if (!parent) { + return false; + } + var keys = getVisitorKeys(parent, options); + for (var i = 0; i < keys.length; ++i) { + var listProp = parent[keys[i]]; + if (Array.isArray(listProp)) { + var idx = listProp.indexOf(node); + if (idx < 0) { + continue; + } + if (side === LEFT_SIDE && idx > 0 && isNode(listProp[idx - 1], options) && matcher(listProp[idx - 1], ancestry, options)) { + return true; + } + if (side === RIGHT_SIDE && idx < listProp.length - 1 && isNode(listProp[idx + 1], options) && matcher(listProp[idx + 1], ancestry, options)) { + return true; + } + } + } + return false; + } + + /** + * Determines if the given node is the `nth` child. + * If `nth` is negative then the position is counted + * from the end of the list of children. + * @param {external:AST} node + * @param {external:AST[]} ancestry + * @param {Integer} nth + * @param {ESQueryOptions|undefined} options + * @returns {boolean} + */ + function nthChild(node, ancestry, nth, options) { + if (nth === 0) { + return false; + } + var _ancestry3 = _slicedToArray(ancestry, 1), + parent = _ancestry3[0]; + if (!parent) { + return false; + } + var keys = getVisitorKeys(parent, options); + for (var i = 0; i < keys.length; ++i) { + var listProp = parent[keys[i]]; + if (Array.isArray(listProp)) { + var idx = nth < 0 ? listProp.length + nth : nth - 1; + if (idx >= 0 && idx < listProp.length && listProp[idx] === node) { + return true; + } + } + } + return false; + } + + /** + * For each selector node marked as a subject, find the portion of the + * selector that the subject must match. + * @param {SelectorAST} selector + * @param {SelectorAST} [ancestor] Defaults to `selector` + * @returns {SelectorAST[]} + */ + function subjects(selector, ancestor) { + if (selector == null || _typeof(selector) != 'object') { + return []; + } + if (ancestor == null) { + ancestor = selector; + } + var results = selector.subject ? [ancestor] : []; + var keys = Object.keys(selector); + for (var i = 0; i < keys.length; ++i) { + var p = keys[i]; + var sel = selector[p]; + results.push.apply(results, _toConsumableArray(subjects(sel, p === 'left' ? sel : ancestor))); + } + return results; + } + + /** + * @callback TraverseVisitor + * @param {?external:AST} node + * @param {?external:AST} parent + * @param {external:AST[]} ancestry + */ + + /** + * From a JS AST and a selector AST, collect all JS AST nodes that + * match the selector. + * @param {external:AST} ast + * @param {?SelectorAST} selector + * @param {TraverseVisitor} visitor + * @param {ESQueryOptions} [options] + * @returns {external:AST[]} + */ + function traverse(ast, selector, visitor, options) { + if (!selector) { + return; + } + var ancestry = []; + var matcher = getMatcher(selector); + var altSubjects = subjects(selector).map(getMatcher); + estraverse.traverse(ast, { + enter: function enter(node, parent) { + if (parent != null) { + ancestry.unshift(parent); + } + if (matcher(node, ancestry, options)) { + if (altSubjects.length) { + for (var i = 0, l = altSubjects.length; i < l; ++i) { + if (altSubjects[i](node, ancestry, options)) { + visitor(node, parent, ancestry); + } + for (var k = 0, m = ancestry.length; k < m; ++k) { + var succeedingAncestry = ancestry.slice(k + 1); + if (altSubjects[i](ancestry[k], succeedingAncestry, options)) { + visitor(ancestry[k], parent, succeedingAncestry); + } + } + } + } else { + visitor(node, parent, ancestry); + } + } + }, + leave: function leave() { + ancestry.shift(); + }, + keys: options && options.visitorKeys, + fallback: options && options.fallback || 'iteration' + }); + } + + /** + * From a JS AST and a selector AST, collect all JS AST nodes that + * match the selector. + * @param {external:AST} ast + * @param {?SelectorAST} selector + * @param {ESQueryOptions} [options] + * @returns {external:AST[]} + */ + function match(ast, selector, options) { + var results = []; + traverse(ast, selector, function (node) { + results.push(node); + }, options); + return results; + } + + /** + * Parse a selector string and return its AST. + * @param {string} selector + * @returns {SelectorAST} + */ + function parse(selector) { + return parser.parse(selector); + } + + /** + * Query the code AST using the selector string. + * @param {external:AST} ast + * @param {string} selector + * @param {ESQueryOptions} [options] + * @returns {external:AST[]} + */ + function query(ast, selector, options) { + return match(ast, parse(selector), options); + } + query.parse = parse; + query.match = match; + query.traverse = traverse; + query.matches = matches; + query.query = query; + + return query; + +}))); diff --git a/node_modules/esquery/dist/esquery.lite.js b/node_modules/esquery/dist/esquery.lite.js new file mode 100644 index 0000000000000000000000000000000000000000..43108768ad4701ada16f3e880078850c10a3de54 --- /dev/null +++ b/node_modules/esquery/dist/esquery.lite.js @@ -0,0 +1,3716 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('estraverse')) : + typeof define === 'function' && define.amd ? define(['estraverse'], factory) : + (global = global || self, global.esquery = factory(global.estraverse)); +}(this, (function (estraverse) { 'use strict'; + + estraverse = estraverse && Object.prototype.hasOwnProperty.call(estraverse, 'default') ? estraverse['default'] : estraverse; + + function _arrayLikeToArray(r, a) { + (null == a || a > r.length) && (a = r.length); + for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; + return n; + } + function _arrayWithHoles(r) { + if (Array.isArray(r)) return r; + } + function _arrayWithoutHoles(r) { + if (Array.isArray(r)) return _arrayLikeToArray(r); + } + function _iterableToArray(r) { + if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); + } + function _iterableToArrayLimit(r, l) { + var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; + if (null != t) { + var e, + n, + i, + u, + a = [], + f = !0, + o = !1; + try { + if (i = (t = t.call(r)).next, 0 === l) { + if (Object(t) !== t) return; + f = !1; + } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); + } catch (r) { + o = !0, n = r; + } finally { + try { + if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; + } finally { + if (o) throw n; + } + } + return a; + } + } + function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + function _slicedToArray(r, e) { + return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); + } + function _toConsumableArray(r) { + return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); + } + function _typeof(o) { + "@babel/helpers - typeof"; + + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { + return typeof o; + } : function (o) { + return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; + }, _typeof(o); + } + function _unsupportedIterableToArray(r, a) { + if (r) { + if ("string" == typeof r) return _arrayLikeToArray(r, a); + var t = {}.toString.call(r).slice(8, -1); + return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; + } + } + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + var parser = createCommonjsModule(function (module) { + /* + * Generated by PEG.js 0.10.0. + * + * http://pegjs.org/ + */ + (function (root, factory) { + if ( module.exports) { + module.exports = factory(); + } + })(commonjsGlobal, function () { + + function peg$subclass(child, parent) { + function ctor() { + this.constructor = child; + } + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + } + function peg$SyntaxError(message, expected, found, location) { + this.message = message; + this.expected = expected; + this.found = found; + this.location = location; + this.name = "SyntaxError"; + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, peg$SyntaxError); + } + } + peg$subclass(peg$SyntaxError, Error); + peg$SyntaxError.buildMessage = function (expected, found) { + var DESCRIBE_EXPECTATION_FNS = { + literal: function literal(expectation) { + return "\"" + literalEscape(expectation.text) + "\""; + }, + "class": function _class(expectation) { + var escapedParts = "", + i; + for (i = 0; i < expectation.parts.length; i++) { + escapedParts += expectation.parts[i] instanceof Array ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) : classEscape(expectation.parts[i]); + } + return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; + }, + any: function any(expectation) { + return "any character"; + }, + end: function end(expectation) { + return "end of input"; + }, + other: function other(expectation) { + return expectation.description; + } + }; + function hex(ch) { + return ch.charCodeAt(0).toString(16).toUpperCase(); + } + function literalEscape(s) { + return s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\0/g, '\\0').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/[\x00-\x0F]/g, function (ch) { + return '\\x0' + hex(ch); + }).replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { + return '\\x' + hex(ch); + }); + } + function classEscape(s) { + return s.replace(/\\/g, '\\\\').replace(/\]/g, '\\]').replace(/\^/g, '\\^').replace(/-/g, '\\-').replace(/\0/g, '\\0').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/[\x00-\x0F]/g, function (ch) { + return '\\x0' + hex(ch); + }).replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { + return '\\x' + hex(ch); + }); + } + function describeExpectation(expectation) { + return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); + } + function describeExpected(expected) { + var descriptions = new Array(expected.length), + i, + j; + for (i = 0; i < expected.length; i++) { + descriptions[i] = describeExpectation(expected[i]); + } + descriptions.sort(); + if (descriptions.length > 0) { + for (i = 1, j = 1; i < descriptions.length; i++) { + if (descriptions[i - 1] !== descriptions[i]) { + descriptions[j] = descriptions[i]; + j++; + } + } + descriptions.length = j; + } + switch (descriptions.length) { + case 1: + return descriptions[0]; + case 2: + return descriptions[0] + " or " + descriptions[1]; + default: + return descriptions.slice(0, -1).join(", ") + ", or " + descriptions[descriptions.length - 1]; + } + } + function describeFound(found) { + return found ? "\"" + literalEscape(found) + "\"" : "end of input"; + } + return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; + }; + function peg$parse(input, options) { + options = options !== void 0 ? options : {}; + var peg$FAILED = {}, + peg$startRuleFunctions = { + start: peg$parsestart + }, + peg$startRuleFunction = peg$parsestart, + peg$c0 = function peg$c0(ss) { + return ss.length === 1 ? ss[0] : { + type: 'matches', + selectors: ss + }; + }, + peg$c1 = function peg$c1() { + return void 0; + }, + peg$c2 = " ", + peg$c3 = peg$literalExpectation(" ", false), + peg$c4 = /^[^ [\],():#!=><~+.]/, + peg$c5 = peg$classExpectation([" ", "[", "]", ",", "(", ")", ":", "#", "!", "=", ">", "<", "~", "+", "."], true, false), + peg$c6 = function peg$c6(i) { + return i.join(''); + }, + peg$c7 = ">", + peg$c8 = peg$literalExpectation(">", false), + peg$c9 = function peg$c9() { + return 'child'; + }, + peg$c10 = "~", + peg$c11 = peg$literalExpectation("~", false), + peg$c12 = function peg$c12() { + return 'sibling'; + }, + peg$c13 = "+", + peg$c14 = peg$literalExpectation("+", false), + peg$c15 = function peg$c15() { + return 'adjacent'; + }, + peg$c16 = function peg$c16() { + return 'descendant'; + }, + peg$c17 = ",", + peg$c18 = peg$literalExpectation(",", false), + peg$c19 = function peg$c19(s, ss) { + return [s].concat(ss.map(function (s) { + return s[3]; + })); + }, + peg$c20 = function peg$c20(op, s) { + if (!op) return s; + return { + type: op, + left: { + type: 'exactNode' + }, + right: s + }; + }, + peg$c21 = function peg$c21(a, ops) { + return ops.reduce(function (memo, rhs) { + return { + type: rhs[0], + left: memo, + right: rhs[1] + }; + }, a); + }, + peg$c22 = "!", + peg$c23 = peg$literalExpectation("!", false), + peg$c24 = function peg$c24(subject, as) { + var b = as.length === 1 ? as[0] : { + type: 'compound', + selectors: as + }; + if (subject) b.subject = true; + return b; + }, + peg$c25 = "*", + peg$c26 = peg$literalExpectation("*", false), + peg$c27 = function peg$c27(a) { + return { + type: 'wildcard', + value: a + }; + }, + peg$c28 = "#", + peg$c29 = peg$literalExpectation("#", false), + peg$c30 = function peg$c30(i) { + return { + type: 'identifier', + value: i + }; + }, + peg$c31 = "[", + peg$c32 = peg$literalExpectation("[", false), + peg$c33 = "]", + peg$c34 = peg$literalExpectation("]", false), + peg$c35 = function peg$c35(v) { + return v; + }, + peg$c36 = /^[>", "<", "!"], false, false), + peg$c38 = "=", + peg$c39 = peg$literalExpectation("=", false), + peg$c40 = function peg$c40(a) { + return (a || '') + '='; + }, + peg$c41 = /^[><]/, + peg$c42 = peg$classExpectation([">", "<"], false, false), + peg$c43 = ".", + peg$c44 = peg$literalExpectation(".", false), + peg$c45 = function peg$c45(a, as) { + return [].concat.apply([a], as).join(''); + }, + peg$c46 = function peg$c46(name, op, value) { + return { + type: 'attribute', + name: name, + operator: op, + value: value + }; + }, + peg$c47 = function peg$c47(name) { + return { + type: 'attribute', + name: name + }; + }, + peg$c48 = "\"", + peg$c49 = peg$literalExpectation("\"", false), + peg$c50 = /^[^\\"]/, + peg$c51 = peg$classExpectation(["\\", "\""], true, false), + peg$c52 = "\\", + peg$c53 = peg$literalExpectation("\\", false), + peg$c54 = peg$anyExpectation(), + peg$c55 = function peg$c55(a, b) { + return a + b; + }, + peg$c56 = function peg$c56(d) { + return { + type: 'literal', + value: strUnescape(d.join('')) + }; + }, + peg$c57 = "'", + peg$c58 = peg$literalExpectation("'", false), + peg$c59 = /^[^\\']/, + peg$c60 = peg$classExpectation(["\\", "'"], true, false), + peg$c61 = /^[0-9]/, + peg$c62 = peg$classExpectation([["0", "9"]], false, false), + peg$c63 = function peg$c63(a, b) { + // Can use `a.flat().join('')` once supported + var leadingDecimals = a ? [].concat.apply([], a).join('') : ''; + return { + type: 'literal', + value: parseFloat(leadingDecimals + b.join('')) + }; + }, + peg$c64 = function peg$c64(i) { + return { + type: 'literal', + value: i + }; + }, + peg$c65 = "type(", + peg$c66 = peg$literalExpectation("type(", false), + peg$c67 = /^[^ )]/, + peg$c68 = peg$classExpectation([" ", ")"], true, false), + peg$c69 = ")", + peg$c70 = peg$literalExpectation(")", false), + peg$c71 = function peg$c71(t) { + return { + type: 'type', + value: t.join('') + }; + }, + peg$c72 = /^[imsu]/, + peg$c73 = peg$classExpectation(["i", "m", "s", "u"], false, false), + peg$c74 = "/", + peg$c75 = peg$literalExpectation("/", false), + peg$c76 = function peg$c76(pattern, flgs) { + return { + type: 'regexp', + value: new RegExp(pattern.join(''), flgs ? flgs.join('') : '') + }; + }, + peg$c77 = /^[^\]\\]/, + peg$c78 = peg$classExpectation(["]", "\\"], true, false), + peg$c79 = function peg$c79(cs) { + return '[' + cs.join('') + ']'; + }, + peg$c80 = function peg$c80(a) { + return '\\' + a; + }, + peg$c81 = /^[^\/\\[]/, + peg$c82 = peg$classExpectation(["/", "\\", "["], true, false), + peg$c83 = function peg$c83(cs) { + return cs.join(''); + }, + peg$c84 = function peg$c84(i, is) { + return { + type: 'field', + name: is.reduce(function (memo, p) { + return memo + p[0] + p[1]; + }, i) + }; + }, + peg$c85 = ":not(", + peg$c86 = peg$literalExpectation(":not(", false), + peg$c87 = function peg$c87(ss) { + return { + type: 'not', + selectors: ss + }; + }, + peg$c88 = ":matches(", + peg$c89 = peg$literalExpectation(":matches(", false), + peg$c90 = function peg$c90(ss) { + return { + type: 'matches', + selectors: ss + }; + }, + peg$c91 = ":is(", + peg$c92 = peg$literalExpectation(":is(", false), + peg$c93 = ":has(", + peg$c94 = peg$literalExpectation(":has(", false), + peg$c95 = function peg$c95(ss) { + return { + type: 'has', + selectors: ss + }; + }, + peg$c96 = ":first-child", + peg$c97 = peg$literalExpectation(":first-child", false), + peg$c98 = function peg$c98() { + return nth(1); + }, + peg$c99 = ":last-child", + peg$c100 = peg$literalExpectation(":last-child", false), + peg$c101 = function peg$c101() { + return nthLast(1); + }, + peg$c102 = ":nth-child(", + peg$c103 = peg$literalExpectation(":nth-child(", false), + peg$c104 = function peg$c104(n) { + return nth(parseInt(n.join(''), 10)); + }, + peg$c105 = ":nth-last-child(", + peg$c106 = peg$literalExpectation(":nth-last-child(", false), + peg$c107 = function peg$c107(n) { + return nthLast(parseInt(n.join(''), 10)); + }, + peg$c108 = ":", + peg$c109 = peg$literalExpectation(":", false), + peg$c110 = function peg$c110(c) { + return { + type: 'class', + name: c + }; + }, + peg$currPos = 0, + peg$posDetailsCache = [{ + line: 1, + column: 1 + }], + peg$maxFailPos = 0, + peg$maxFailExpected = [], + peg$resultsCache = {}, + peg$result; + if ("startRule" in options) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); + } + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + function peg$literalExpectation(text, ignoreCase) { + return { + type: "literal", + text: text, + ignoreCase: ignoreCase + }; + } + function peg$classExpectation(parts, inverted, ignoreCase) { + return { + type: "class", + parts: parts, + inverted: inverted, + ignoreCase: ignoreCase + }; + } + function peg$anyExpectation() { + return { + type: "any" + }; + } + function peg$endExpectation() { + return { + type: "end" + }; + } + function peg$computePosDetails(pos) { + var details = peg$posDetailsCache[pos], + p; + if (details) { + return details; + } else { + p = pos - 1; + while (!peg$posDetailsCache[p]) { + p--; + } + details = peg$posDetailsCache[p]; + details = { + line: details.line, + column: details.column + }; + while (p < pos) { + if (input.charCodeAt(p) === 10) { + details.line++; + details.column = 1; + } else { + details.column++; + } + p++; + } + peg$posDetailsCache[pos] = details; + return details; + } + } + function peg$computeLocation(startPos, endPos) { + var startPosDetails = peg$computePosDetails(startPos), + endPosDetails = peg$computePosDetails(endPos); + return { + start: { + offset: startPos, + line: startPosDetails.line, + column: startPosDetails.column + }, + end: { + offset: endPos, + line: endPosDetails.line, + column: endPosDetails.column + } + }; + } + function peg$fail(expected) { + if (peg$currPos < peg$maxFailPos) { + return; + } + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; + } + peg$maxFailExpected.push(expected); + } + function peg$buildStructuredError(expected, found, location) { + return new peg$SyntaxError(peg$SyntaxError.buildMessage(expected, found), expected, found, location); + } + function peg$parsestart() { + var s0, s1, s2, s3; + var key = peg$currPos * 36 + 0, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + s2 = peg$parseselectors(); + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c0(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + s1 = peg$c1(); + } + s0 = s1; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parse_() { + var s0, s1; + var key = peg$currPos * 36 + 1, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = []; + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c3); + } + } + while (s1 !== peg$FAILED) { + s0.push(s1); + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c3); + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseidentifierName() { + var s0, s1, s2; + var key = peg$currPos * 36 + 2, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = []; + if (peg$c4.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c5); + } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + if (peg$c4.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c5); + } + } + } + } else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s1 = peg$c6(s1); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsebinaryOp() { + var s0, s1, s2, s3; + var key = peg$currPos * 36 + 3, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 62) { + s2 = peg$c7; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c8); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c9(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c10; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c11); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c12(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c13; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c14); + } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + s1 = peg$c15(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c3); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s1 = peg$c16(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsehasSelectors() { + var s0, s1, s2, s3, s4, s5, s6, s7; + var key = peg$currPos * 36 + 4, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parsehasSelector(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parsehasSelector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parsehasSelector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c19(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseselectors() { + var s0, s1, s2, s3, s4, s5, s6, s7; + var key = peg$currPos * 36 + 5, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseselector(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseselector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c18); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseselector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c19(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsehasSelector() { + var s0, s1, s2; + var key = peg$currPos * 36 + 6, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parsebinaryOp(); + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseselector(); + if (s2 !== peg$FAILED) { + s1 = peg$c20(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseselector() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 7, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parsesequence(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parsebinaryOp(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesequence(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parsebinaryOp(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesequence(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c21(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsesequence() { + var s0, s1, s2, s3; + var key = peg$currPos * 36 + 8, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 33) { + s1 = peg$c22; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c23); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseatom(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseatom(); + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = peg$c24(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseatom() { + var s0; + var key = peg$currPos * 36 + 9, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$parsewildcard(); + if (s0 === peg$FAILED) { + s0 = peg$parseidentifier(); + if (s0 === peg$FAILED) { + s0 = peg$parseattr(); + if (s0 === peg$FAILED) { + s0 = peg$parsefield(); + if (s0 === peg$FAILED) { + s0 = peg$parsenegation(); + if (s0 === peg$FAILED) { + s0 = peg$parsematches(); + if (s0 === peg$FAILED) { + s0 = peg$parseis(); + if (s0 === peg$FAILED) { + s0 = peg$parsehas(); + if (s0 === peg$FAILED) { + s0 = peg$parsefirstChild(); + if (s0 === peg$FAILED) { + s0 = peg$parselastChild(); + if (s0 === peg$FAILED) { + s0 = peg$parsenthChild(); + if (s0 === peg$FAILED) { + s0 = peg$parsenthLastChild(); + if (s0 === peg$FAILED) { + s0 = peg$parseclass(); + } + } + } + } + } + } + } + } + } + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsewildcard() { + var s0, s1; + var key = peg$currPos * 36 + 10, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 42) { + s1 = peg$c25; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c26); + } + } + if (s1 !== peg$FAILED) { + s1 = peg$c27(s1); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseidentifier() { + var s0, s1, s2; + var key = peg$currPos * 36 + 11, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 35) { + s1 = peg$c28; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c29); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + s1 = peg$c30(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattr() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 12, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c31; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c32); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrValue(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s5 = peg$c33; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c34); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c35(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrOps() { + var s0, s1, s2; + var key = peg$currPos * 36 + 13, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (peg$c36.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c37); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c39); + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c40(s1); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + if (peg$c41.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + { + peg$fail(peg$c42); + } + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrEqOps() { + var s0, s1, s2; + var key = peg$currPos * 36 + 14, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 33) { + s1 = peg$c22; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c23); + } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c39); + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c40(s1); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrName() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 15, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseidentifierName(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c43; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseidentifierName(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c43; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseidentifierName(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c45(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseattrValue() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 16, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrEqOps(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetype(); + if (s5 === peg$FAILED) { + s5 = peg$parseregex(); + } + if (s5 !== peg$FAILED) { + s1 = peg$c46(s1, s3, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrOps(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + s5 = peg$parsestring(); + if (s5 === peg$FAILED) { + s5 = peg$parsenumber(); + if (s5 === peg$FAILED) { + s5 = peg$parsepath(); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c46(s1, s3, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s1 = peg$c47(s1); + } + s0 = s1; + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsestring() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 17, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 34) { + s1 = peg$c48; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c49); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c50.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c51); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c50.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c51); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 34) { + s3 = peg$c48; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c49); + } + } + if (s3 !== peg$FAILED) { + s1 = peg$c56(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 39) { + s1 = peg$c57; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c58); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c59.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c60); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c59.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c60); + } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s5 !== peg$FAILED) { + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s3 = peg$c57; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c58); + } + } + if (s3 !== peg$FAILED) { + s1 = peg$c56(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenumber() { + var s0, s1, s2, s3; + var key = peg$currPos * 36 + 18, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$currPos; + s2 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s3 = peg$c43; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + s1 = peg$c63(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsepath() { + var s0, s1; + var key = peg$currPos * 36 + 19, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = peg$parseidentifierName(); + if (s1 !== peg$FAILED) { + s1 = peg$c64(s1); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsetype() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 20, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c65) { + s1 = peg$c65; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c66); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c67.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c68); + } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c67.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c68); + } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c71(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseflags() { + var s0, s1; + var key = peg$currPos * 36 + 21, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = []; + if (peg$c72.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c73); + } + } + if (s1 !== peg$FAILED) { + while (s1 !== peg$FAILED) { + s0.push(s1); + if (peg$c72.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c73); + } + } + } + } else { + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseregex() { + var s0, s1, s2, s3, s4; + var key = peg$currPos * 36 + 22, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 47) { + s1 = peg$c74; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c75); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsere_character_class(); + if (s3 === peg$FAILED) { + s3 = peg$parsere_escape(); + if (s3 === peg$FAILED) { + s3 = peg$parsere_chars(); + } + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsere_character_class(); + if (s3 === peg$FAILED) { + s3 = peg$parsere_escape(); + if (s3 === peg$FAILED) { + s3 = peg$parsere_chars(); + } + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s3 = peg$c74; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c75); + } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseflags(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + s1 = peg$c76(s2, s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsere_character_class() { + var s0, s1, s2, s3; + var key = peg$currPos * 36 + 23, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c31; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c32); + } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c77.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c78); + } + } + if (s3 === peg$FAILED) { + s3 = peg$parsere_escape(); + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c77.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c78); + } + } + if (s3 === peg$FAILED) { + s3 = peg$parsere_escape(); + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c33; + peg$currPos++; + } else { + s3 = peg$FAILED; + { + peg$fail(peg$c34); + } + } + if (s3 !== peg$FAILED) { + s1 = peg$c79(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsere_escape() { + var s0, s1, s2; + var key = peg$currPos * 36 + 24, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s1 = peg$c52; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c53); + } + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c54); + } + } + if (s2 !== peg$FAILED) { + s1 = peg$c80(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsere_chars() { + var s0, s1, s2; + var key = peg$currPos * 36 + 25, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + s1 = []; + if (peg$c81.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c82); + } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + if (peg$c81.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + { + peg$fail(peg$c82); + } + } + } + } else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + s1 = peg$c83(s1); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsefield() { + var s0, s1, s2, s3, s4, s5, s6; + var key = peg$currPos * 36 + 26, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c43; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c43; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseidentifierName(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c43; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c44); + } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseidentifierName(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + s1 = peg$c84(s2, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenegation() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 27, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c85) { + s1 = peg$c85; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c86); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c87(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsematches() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 28, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 9) === peg$c88) { + s1 = peg$c88; + peg$currPos += 9; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c89); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c90(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseis() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 29, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 4) === peg$c91) { + s1 = peg$c91; + peg$currPos += 4; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c92); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c90(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsehas() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 30, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c93) { + s1 = peg$c93; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c94); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parsehasSelectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c95(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsefirstChild() { + var s0, s1; + var key = peg$currPos * 36 + 31, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 12) === peg$c96) { + s1 = peg$c96; + peg$currPos += 12; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c97); + } + } + if (s1 !== peg$FAILED) { + s1 = peg$c98(); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parselastChild() { + var s0, s1; + var key = peg$currPos * 36 + 32, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c99) { + s1 = peg$c99; + peg$currPos += 11; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c100); + } + } + if (s1 !== peg$FAILED) { + s1 = peg$c101(); + } + s0 = s1; + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenthChild() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 33, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c102) { + s1 = peg$c102; + peg$currPos += 11; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c103); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c104(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parsenthLastChild() { + var s0, s1, s2, s3, s4, s5; + var key = peg$currPos * 36 + 34, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.substr(peg$currPos, 16) === peg$c105) { + s1 = peg$c105; + peg$currPos += 16; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c106); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + { + peg$fail(peg$c62); + } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + { + peg$fail(peg$c70); + } + } + if (s5 !== peg$FAILED) { + s1 = peg$c107(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function peg$parseclass() { + var s0, s1, s2; + var key = peg$currPos * 36 + 35, + cached = peg$resultsCache[key]; + if (cached) { + peg$currPos = cached.nextPos; + return cached.result; + } + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s1 = peg$c108; + peg$currPos++; + } else { + s1 = peg$FAILED; + { + peg$fail(peg$c109); + } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + s1 = peg$c110(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + peg$resultsCache[key] = { + nextPos: peg$currPos, + result: s0 + }; + return s0; + } + function nth(n) { + return { + type: 'nth-child', + index: { + type: 'literal', + value: n + } + }; + } + function nthLast(n) { + return { + type: 'nth-last-child', + index: { + type: 'literal', + value: n + } + }; + } + function strUnescape(s) { + return s.replace(/\\(.)/g, function (match, ch) { + switch (ch) { + case 'b': + return '\b'; + case 'f': + return '\f'; + case 'n': + return '\n'; + case 'r': + return '\r'; + case 't': + return '\t'; + case 'v': + return '\v'; + default: + return ch; + } + }); + } + peg$result = peg$startRuleFunction(); + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail(peg$endExpectation()); + } + throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)); + } + } + return { + SyntaxError: peg$SyntaxError, + parse: peg$parse + }; + }); + }); + + /** + * @typedef {"LEFT_SIDE"|"RIGHT_SIDE"} Side + */ + + var LEFT_SIDE = 'LEFT_SIDE'; + var RIGHT_SIDE = 'RIGHT_SIDE'; + + /** + * @external AST + * @see https://esprima.readthedocs.io/en/latest/syntax-tree-format.html + */ + + /** + * One of the rules of `grammar.pegjs` + * @typedef {PlainObject} SelectorAST + * @see grammar.pegjs + */ + + /** + * The `sequence` production of `grammar.pegjs` + * @typedef {PlainObject} SelectorSequenceAST + */ + + /** + * Get the value of a property which may be multiple levels down + * in the object. + * @param {?PlainObject} obj + * @param {string[]} keys + * @returns {undefined|boolean|string|number|external:AST} + */ + function getPath(obj, keys) { + for (var i = 0; i < keys.length; ++i) { + if (obj == null) { + return obj; + } + obj = obj[keys[i]]; + } + return obj; + } + + /** + * Determine whether `node` can be reached by following `path`, + * starting at `ancestor`. + * @param {?external:AST} node + * @param {?external:AST} ancestor + * @param {string[]} path + * @param {Integer} fromPathIndex + * @returns {boolean} + */ + function inPath(node, ancestor, path, fromPathIndex) { + var current = ancestor; + for (var i = fromPathIndex; i < path.length; ++i) { + if (current == null) { + return false; + } + var field = current[path[i]]; + if (Array.isArray(field)) { + for (var k = 0; k < field.length; ++k) { + if (inPath(node, field[k], path, i + 1)) { + return true; + } + } + return false; + } + current = field; + } + return node === current; + } + + /** + * A generated matcher function for a selector. + * @callback SelectorMatcher + * @param {?SelectorAST} selector + * @param {external:AST[]} [ancestry=[]] + * @param {ESQueryOptions} [options] + * @returns {void} + */ + + /** + * A WeakMap for holding cached matcher functions for selectors. + * @type {WeakMap} + */ + var MATCHER_CACHE = typeof WeakMap === 'function' ? new WeakMap() : null; + + /** + * Look up a matcher function for `selector` in the cache. + * If it does not exist, generate it with `generateMatcher` and add it to the cache. + * In engines without WeakMap, the caching is skipped and matchers are generated with every call. + * @param {?SelectorAST} selector + * @returns {SelectorMatcher} + */ + function getMatcher(selector) { + if (selector == null) { + return function () { + return true; + }; + } + if (MATCHER_CACHE != null) { + var matcher = MATCHER_CACHE.get(selector); + if (matcher != null) { + return matcher; + } + matcher = generateMatcher(selector); + MATCHER_CACHE.set(selector, matcher); + return matcher; + } + return generateMatcher(selector); + } + + /** + * Create a matcher function for `selector`, + * @param {?SelectorAST} selector + * @returns {SelectorMatcher} + */ + function generateMatcher(selector) { + switch (selector.type) { + case 'wildcard': + return function () { + return true; + }; + case 'identifier': + { + var value = selector.value.toLowerCase(); + return function (node, ancestry, options) { + var nodeTypeKey = options && options.nodeTypeKey || 'type'; + return value === node[nodeTypeKey].toLowerCase(); + }; + } + case 'exactNode': + return function (node, ancestry) { + return ancestry.length === 0; + }; + case 'field': + { + var path = selector.name.split('.'); + return function (node, ancestry) { + var ancestor = ancestry[path.length - 1]; + return inPath(node, ancestor, path, 0); + }; + } + case 'matches': + { + var matchers = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + for (var i = 0; i < matchers.length; ++i) { + if (matchers[i](node, ancestry, options)) { + return true; + } + } + return false; + }; + } + case 'compound': + { + var _matchers = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + for (var i = 0; i < _matchers.length; ++i) { + if (!_matchers[i](node, ancestry, options)) { + return false; + } + } + return true; + }; + } + case 'not': + { + var _matchers2 = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + for (var i = 0; i < _matchers2.length; ++i) { + if (_matchers2[i](node, ancestry, options)) { + return false; + } + } + return true; + }; + } + case 'has': + { + var _matchers3 = selector.selectors.map(getMatcher); + return function (node, ancestry, options) { + var result = false; + var a = []; + estraverse.traverse(node, { + enter: function enter(node, parent) { + if (parent != null) { + a.unshift(parent); + } + for (var i = 0; i < _matchers3.length; ++i) { + if (_matchers3[i](node, a, options)) { + result = true; + this["break"](); + return; + } + } + }, + leave: function leave() { + a.shift(); + }, + keys: options && options.visitorKeys, + fallback: options && options.fallback || 'iteration' + }); + return result; + }; + } + case 'child': + { + var left = getMatcher(selector.left); + var right = getMatcher(selector.right); + return function (node, ancestry, options) { + if (ancestry.length > 0 && right(node, ancestry, options)) { + return left(ancestry[0], ancestry.slice(1), options); + } + return false; + }; + } + case 'descendant': + { + var _left = getMatcher(selector.left); + var _right = getMatcher(selector.right); + return function (node, ancestry, options) { + if (_right(node, ancestry, options)) { + for (var i = 0, l = ancestry.length; i < l; ++i) { + if (_left(ancestry[i], ancestry.slice(i + 1), options)) { + return true; + } + } + } + return false; + }; + } + case 'attribute': + { + var _path = selector.name.split('.'); + switch (selector.operator) { + case void 0: + return function (node) { + return getPath(node, _path) != null; + }; + case '=': + switch (selector.value.type) { + case 'regexp': + return function (node) { + var p = getPath(node, _path); + return typeof p === 'string' && selector.value.value.test(p); + }; + case 'literal': + { + var literal = "".concat(selector.value.value); + return function (node) { + return literal === "".concat(getPath(node, _path)); + }; + } + case 'type': + return function (node) { + return selector.value.value === _typeof(getPath(node, _path)); + }; + } + throw new Error("Unknown selector value type: ".concat(selector.value.type)); + case '!=': + switch (selector.value.type) { + case 'regexp': + return function (node) { + return !selector.value.value.test(getPath(node, _path)); + }; + case 'literal': + { + var _literal = "".concat(selector.value.value); + return function (node) { + return _literal !== "".concat(getPath(node, _path)); + }; + } + case 'type': + return function (node) { + return selector.value.value !== _typeof(getPath(node, _path)); + }; + } + throw new Error("Unknown selector value type: ".concat(selector.value.type)); + case '<=': + return function (node) { + return getPath(node, _path) <= selector.value.value; + }; + case '<': + return function (node) { + return getPath(node, _path) < selector.value.value; + }; + case '>': + return function (node) { + return getPath(node, _path) > selector.value.value; + }; + case '>=': + return function (node) { + return getPath(node, _path) >= selector.value.value; + }; + } + throw new Error("Unknown operator: ".concat(selector.operator)); + } + case 'sibling': + { + var _left2 = getMatcher(selector.left); + var _right2 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right2(node, ancestry, options) && sibling(node, _left2, ancestry, LEFT_SIDE, options) || selector.left.subject && _left2(node, ancestry, options) && sibling(node, _right2, ancestry, RIGHT_SIDE, options); + }; + } + case 'adjacent': + { + var _left3 = getMatcher(selector.left); + var _right3 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right3(node, ancestry, options) && adjacent(node, _left3, ancestry, LEFT_SIDE, options) || selector.right.subject && _left3(node, ancestry, options) && adjacent(node, _right3, ancestry, RIGHT_SIDE, options); + }; + } + case 'nth-child': + { + var nth = selector.index.value; + var _right4 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right4(node, ancestry, options) && nthChild(node, ancestry, nth, options); + }; + } + case 'nth-last-child': + { + var _nth = -selector.index.value; + var _right5 = getMatcher(selector.right); + return function (node, ancestry, options) { + return _right5(node, ancestry, options) && nthChild(node, ancestry, _nth, options); + }; + } + case 'class': + { + var name = selector.name.toLowerCase(); + return function (node, ancestry, options) { + if (options && options.matchClass) { + return options.matchClass(selector.name, node, ancestry); + } + if (options && options.nodeTypeKey) return false; + switch (name) { + case 'statement': + if (node.type.slice(-9) === 'Statement') return true; + // fallthrough: interface Declaration <: Statement { } + case 'declaration': + return node.type.slice(-11) === 'Declaration'; + case 'pattern': + if (node.type.slice(-7) === 'Pattern') return true; + // fallthrough: interface Expression <: Node, Pattern { } + case 'expression': + return node.type.slice(-10) === 'Expression' || node.type.slice(-7) === 'Literal' || node.type === 'Identifier' && (ancestry.length === 0 || ancestry[0].type !== 'MetaProperty') || node.type === 'MetaProperty'; + case 'function': + return node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression'; + } + throw new Error("Unknown class name: ".concat(selector.name)); + }; + } + } + throw new Error("Unknown selector type: ".concat(selector.type)); + } + + /** + * @callback TraverseOptionFallback + * @param {external:AST} node The given node. + * @returns {string[]} An array of visitor keys for the given node. + */ + + /** + * @callback ClassMatcher + * @param {string} className The name of the class to match. + * @param {external:AST} node The node to match against. + * @param {Array} ancestry The ancestry of the node. + * @returns {boolean} True if the node matches the class, false if not. + */ + + /** + * @typedef {object} ESQueryOptions + * @property {string} [nodeTypeKey="type"] By passing `nodeTypeKey`, we can allow other ASTs to use ESQuery. + * @property { { [nodeType: string]: string[] } } [visitorKeys] By passing `visitorKeys` mapping, we can extend the properties of the nodes that traverse the node. + * @property {TraverseOptionFallback} [fallback] By passing `fallback` option, we can control the properties of traversing nodes when encountering unknown nodes. + * @property {ClassMatcher} [matchClass] By passing `matchClass` option, we can customize the interpretation of classes. + */ + + /** + * Given a `node` and its ancestors, determine if `node` is matched + * by `selector`. + * @param {?external:AST} node + * @param {?SelectorAST} selector + * @param {external:AST[]} [ancestry=[]] + * @param {ESQueryOptions} [options] + * @throws {Error} Unknowns (operator, class name, selector type, or + * selector value type) + * @returns {boolean} + */ + function matches(node, selector, ancestry, options) { + if (!selector) { + return true; + } + if (!node) { + return false; + } + if (!ancestry) { + ancestry = []; + } + return getMatcher(selector)(node, ancestry, options); + } + + /** + * Get visitor keys of a given node. + * @param {external:AST} node The AST node to get keys. + * @param {ESQueryOptions|undefined} options + * @returns {string[]} Visitor keys of the node. + */ + function getVisitorKeys(node, options) { + var nodeTypeKey = options && options.nodeTypeKey || 'type'; + var nodeType = node[nodeTypeKey]; + if (options && options.visitorKeys && options.visitorKeys[nodeType]) { + return options.visitorKeys[nodeType]; + } + if (estraverse.VisitorKeys[nodeType]) { + return estraverse.VisitorKeys[nodeType]; + } + if (options && typeof options.fallback === 'function') { + return options.fallback(node); + } + // 'iteration' fallback + return Object.keys(node).filter(function (key) { + return key !== nodeTypeKey; + }); + } + + /** + * Check whether the given value is an ASTNode or not. + * @param {any} node The value to check. + * @param {ESQueryOptions|undefined} options The options to use. + * @returns {boolean} `true` if the value is an ASTNode. + */ + function isNode(node, options) { + var nodeTypeKey = options && options.nodeTypeKey || 'type'; + return node !== null && _typeof(node) === 'object' && typeof node[nodeTypeKey] === 'string'; + } + + /** + * Determines if the given node has a sibling that matches the + * given selector matcher. + * @param {external:AST} node + * @param {SelectorMatcher} matcher + * @param {external:AST[]} ancestry + * @param {Side} side + * @param {ESQueryOptions|undefined} options + * @returns {boolean} + */ + function sibling(node, matcher, ancestry, side, options) { + var _ancestry = _slicedToArray(ancestry, 1), + parent = _ancestry[0]; + if (!parent) { + return false; + } + var keys = getVisitorKeys(parent, options); + for (var i = 0; i < keys.length; ++i) { + var listProp = parent[keys[i]]; + if (Array.isArray(listProp)) { + var startIndex = listProp.indexOf(node); + if (startIndex < 0) { + continue; + } + var lowerBound = void 0, + upperBound = void 0; + if (side === LEFT_SIDE) { + lowerBound = 0; + upperBound = startIndex; + } else { + lowerBound = startIndex + 1; + upperBound = listProp.length; + } + for (var k = lowerBound; k < upperBound; ++k) { + if (isNode(listProp[k], options) && matcher(listProp[k], ancestry, options)) { + return true; + } + } + } + } + return false; + } + + /** + * Determines if the given node has an adjacent sibling that matches + * the given selector matcher. + * @param {external:AST} node + * @param {SelectorMatcher} matcher + * @param {external:AST[]} ancestry + * @param {Side} side + * @param {ESQueryOptions|undefined} options + * @returns {boolean} + */ + function adjacent(node, matcher, ancestry, side, options) { + var _ancestry2 = _slicedToArray(ancestry, 1), + parent = _ancestry2[0]; + if (!parent) { + return false; + } + var keys = getVisitorKeys(parent, options); + for (var i = 0; i < keys.length; ++i) { + var listProp = parent[keys[i]]; + if (Array.isArray(listProp)) { + var idx = listProp.indexOf(node); + if (idx < 0) { + continue; + } + if (side === LEFT_SIDE && idx > 0 && isNode(listProp[idx - 1], options) && matcher(listProp[idx - 1], ancestry, options)) { + return true; + } + if (side === RIGHT_SIDE && idx < listProp.length - 1 && isNode(listProp[idx + 1], options) && matcher(listProp[idx + 1], ancestry, options)) { + return true; + } + } + } + return false; + } + + /** + * Determines if the given node is the `nth` child. + * If `nth` is negative then the position is counted + * from the end of the list of children. + * @param {external:AST} node + * @param {external:AST[]} ancestry + * @param {Integer} nth + * @param {ESQueryOptions|undefined} options + * @returns {boolean} + */ + function nthChild(node, ancestry, nth, options) { + if (nth === 0) { + return false; + } + var _ancestry3 = _slicedToArray(ancestry, 1), + parent = _ancestry3[0]; + if (!parent) { + return false; + } + var keys = getVisitorKeys(parent, options); + for (var i = 0; i < keys.length; ++i) { + var listProp = parent[keys[i]]; + if (Array.isArray(listProp)) { + var idx = nth < 0 ? listProp.length + nth : nth - 1; + if (idx >= 0 && idx < listProp.length && listProp[idx] === node) { + return true; + } + } + } + return false; + } + + /** + * For each selector node marked as a subject, find the portion of the + * selector that the subject must match. + * @param {SelectorAST} selector + * @param {SelectorAST} [ancestor] Defaults to `selector` + * @returns {SelectorAST[]} + */ + function subjects(selector, ancestor) { + if (selector == null || _typeof(selector) != 'object') { + return []; + } + if (ancestor == null) { + ancestor = selector; + } + var results = selector.subject ? [ancestor] : []; + var keys = Object.keys(selector); + for (var i = 0; i < keys.length; ++i) { + var p = keys[i]; + var sel = selector[p]; + results.push.apply(results, _toConsumableArray(subjects(sel, p === 'left' ? sel : ancestor))); + } + return results; + } + + /** + * @callback TraverseVisitor + * @param {?external:AST} node + * @param {?external:AST} parent + * @param {external:AST[]} ancestry + */ + + /** + * From a JS AST and a selector AST, collect all JS AST nodes that + * match the selector. + * @param {external:AST} ast + * @param {?SelectorAST} selector + * @param {TraverseVisitor} visitor + * @param {ESQueryOptions} [options] + * @returns {external:AST[]} + */ + function traverse(ast, selector, visitor, options) { + if (!selector) { + return; + } + var ancestry = []; + var matcher = getMatcher(selector); + var altSubjects = subjects(selector).map(getMatcher); + estraverse.traverse(ast, { + enter: function enter(node, parent) { + if (parent != null) { + ancestry.unshift(parent); + } + if (matcher(node, ancestry, options)) { + if (altSubjects.length) { + for (var i = 0, l = altSubjects.length; i < l; ++i) { + if (altSubjects[i](node, ancestry, options)) { + visitor(node, parent, ancestry); + } + for (var k = 0, m = ancestry.length; k < m; ++k) { + var succeedingAncestry = ancestry.slice(k + 1); + if (altSubjects[i](ancestry[k], succeedingAncestry, options)) { + visitor(ancestry[k], parent, succeedingAncestry); + } + } + } + } else { + visitor(node, parent, ancestry); + } + } + }, + leave: function leave() { + ancestry.shift(); + }, + keys: options && options.visitorKeys, + fallback: options && options.fallback || 'iteration' + }); + } + + /** + * From a JS AST and a selector AST, collect all JS AST nodes that + * match the selector. + * @param {external:AST} ast + * @param {?SelectorAST} selector + * @param {ESQueryOptions} [options] + * @returns {external:AST[]} + */ + function match(ast, selector, options) { + var results = []; + traverse(ast, selector, function (node) { + results.push(node); + }, options); + return results; + } + + /** + * Parse a selector string and return its AST. + * @param {string} selector + * @returns {SelectorAST} + */ + function parse(selector) { + return parser.parse(selector); + } + + /** + * Query the code AST using the selector string. + * @param {external:AST} ast + * @param {string} selector + * @param {ESQueryOptions} [options] + * @returns {external:AST[]} + */ + function query(ast, selector, options) { + return match(ast, parse(selector), options); + } + query.parse = parse; + query.match = match; + query.traverse = traverse; + query.matches = matches; + query.query = query; + + return query; + +}))); diff --git a/node_modules/esquery/dist/esquery.lite.min.js b/node_modules/esquery/dist/esquery.lite.min.js new file mode 100644 index 0000000000000000000000000000000000000000..9f19c09af0391b4ccf9078c7ea3630d1bdb44ace --- /dev/null +++ b/node_modules/esquery/dist/esquery.lite.min.js @@ -0,0 +1,2 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("estraverse")):"function"==typeof define&&define.amd?define(["estraverse"],e):(t=t||self).esquery=e(t.estraverse)}(this,(function(t){"use strict";function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r0){for(e=1,n=1;e<~+.]/,h=yt([" ","[","]",",","(",")",":","#","!","=",">","<","~","+","."],!0,!1),p=dt(">",!1),v=dt("~",!1),d=dt("+",!1),y=dt(",",!1),A=function(t,e){return[t].concat(e.map((function(t){return t[3]})))},x=dt("!",!1),g=dt("*",!1),P=dt("#",!1),m=dt("[",!1),b=dt("]",!1),C=/^[>","<","!"],!1,!1),j=dt("=",!1),E=function(t){return(t||"")+"="},S=/^[><]/,k=yt([">","<"],!1,!1),I=dt(".",!1),T=function(t,e,r){return{type:"attribute",name:t,operator:e,value:r}},F=dt('"',!1),K=/^[^\\"]/,D=yt(["\\",'"'],!0,!1),O=dt("\\",!1),L={type:"any"},R=function(t,e){return t+e},M=function(t){return{type:"literal",value:(e=t.join(""),e.replace(/\\(.)/g,(function(t,e){switch(e){case"b":return"\b";case"f":return"\f";case"n":return"\n";case"r":return"\r";case"t":return"\t";case"v":return"\v";default:return e}})))};var e},U=dt("'",!1),_=/^[^\\']/,q=yt(["\\","'"],!0,!1),G=/^[0-9]/,H=yt([["0","9"]],!1,!1),N=dt("type(",!1),V=/^[^ )]/,W=yt([" ",")"],!0,!1),$=dt(")",!1),z=/^[imsu]/,B=yt(["i","m","s","u"],!1,!1),J=dt("/",!1),Q=/^[^\]\\]/,X=yt(["]","\\"],!0,!1),Y=/^[^\/\\[]/,Z=yt(["/","\\","["],!0,!1),tt=dt(":not(",!1),et=dt(":matches(",!1),rt=function(t){return{type:"matches",selectors:t}},nt=dt(":is(",!1),ut=dt(":has(",!1),ot=dt(":first-child",!1),at=dt(":last-child",!1),st=dt(":nth-child(",!1),ct=dt(":nth-last-child(",!1),it=dt(":",!1),lt=0,ft=[{line:1,column:1}],ht=0,pt=[],vt={};if("startRule"in r){if(!(r.startRule in c))throw new Error("Can't start parsing from rule \""+r.startRule+'".');i=c[r.startRule]}function dt(t,e){return{type:"literal",text:t,ignoreCase:e}}function yt(t,e,r){return{type:"class",parts:t,inverted:e,ignoreCase:r}}function At(t){var r,n=ft[t];if(n)return n;for(r=t-1;!ft[r];)r--;for(n={line:(n=ft[r]).line,column:n.column};rht&&(ht=lt,pt=[]),pt.push(t))}function Pt(){var t,e,r,n,u=36*lt+0,o=vt[u];return o?(lt=o.nextPos,o.result):(t=lt,(e=mt())!==s&&(r=wt())!==s&&mt()!==s?t=e=1===(n=r).length?n[0]:{type:"matches",selectors:n}:(lt=t,t=s),t===s&&(t=lt,(e=mt())!==s&&(e=void 0),t=e),vt[u]={nextPos:lt,result:t},t)}function mt(){var t,r,n=36*lt+1,u=vt[n];if(u)return lt=u.nextPos,u.result;for(t=[],32===e.charCodeAt(lt)?(r=" ",lt++):(r=s,gt(l));r!==s;)t.push(r),32===e.charCodeAt(lt)?(r=" ",lt++):(r=s,gt(l));return vt[n]={nextPos:lt,result:t},t}function bt(){var t,r,n,u=36*lt+2,o=vt[u];if(o)return lt=o.nextPos,o.result;if(r=[],f.test(e.charAt(lt))?(n=e.charAt(lt),lt++):(n=s,gt(h)),n!==s)for(;n!==s;)r.push(n),f.test(e.charAt(lt))?(n=e.charAt(lt),lt++):(n=s,gt(h));else r=s;return r!==s&&(r=r.join("")),t=r,vt[u]={nextPos:lt,result:t},t}function Ct(){var t,r,n,u=36*lt+3,o=vt[u];return o?(lt=o.nextPos,o.result):(t=lt,(r=mt())!==s?(62===e.charCodeAt(lt)?(n=">",lt++):(n=s,gt(p)),n!==s&&mt()!==s?t=r="child":(lt=t,t=s)):(lt=t,t=s),t===s&&(t=lt,(r=mt())!==s?(126===e.charCodeAt(lt)?(n="~",lt++):(n=s,gt(v)),n!==s&&mt()!==s?t=r="sibling":(lt=t,t=s)):(lt=t,t=s),t===s&&(t=lt,(r=mt())!==s?(43===e.charCodeAt(lt)?(n="+",lt++):(n=s,gt(d)),n!==s&&mt()!==s?t=r="adjacent":(lt=t,t=s)):(lt=t,t=s),t===s&&(t=lt,32===e.charCodeAt(lt)?(r=" ",lt++):(r=s,gt(l)),r!==s&&(n=mt())!==s?t=r="descendant":(lt=t,t=s)))),vt[u]={nextPos:lt,result:t},t)}function wt(){var t,r,n,u,o,a,c,i,l=36*lt+5,f=vt[l];if(f)return lt=f.nextPos,f.result;if(t=lt,(r=Et())!==s){for(n=[],u=lt,(o=mt())!==s?(44===e.charCodeAt(lt)?(a=",",lt++):(a=s,gt(y)),a!==s&&(c=mt())!==s&&(i=Et())!==s?u=o=[o,a,c,i]:(lt=u,u=s)):(lt=u,u=s);u!==s;)n.push(u),u=lt,(o=mt())!==s?(44===e.charCodeAt(lt)?(a=",",lt++):(a=s,gt(y)),a!==s&&(c=mt())!==s&&(i=Et())!==s?u=o=[o,a,c,i]:(lt=u,u=s)):(lt=u,u=s);n!==s?t=r=A(r,n):(lt=t,t=s)}else lt=t,t=s;return vt[l]={nextPos:lt,result:t},t}function jt(){var t,e,r,n,u,o=36*lt+6,a=vt[o];return a?(lt=a.nextPos,a.result):(t=lt,(e=Ct())===s&&(e=null),e!==s&&(r=Et())!==s?(u=r,t=e=(n=e)?{type:n,left:{type:"exactNode"},right:u}:u):(lt=t,t=s),vt[o]={nextPos:lt,result:t},t)}function Et(){var t,e,r,n,u,o,a,c=36*lt+7,i=vt[c];if(i)return lt=i.nextPos,i.result;if(t=lt,(e=St())!==s){for(r=[],n=lt,(u=Ct())!==s&&(o=St())!==s?n=u=[u,o]:(lt=n,n=s);n!==s;)r.push(n),n=lt,(u=Ct())!==s&&(o=St())!==s?n=u=[u,o]:(lt=n,n=s);r!==s?(a=e,t=e=r.reduce((function(t,e){return{type:e[0],left:t,right:e[1]}}),a)):(lt=t,t=s)}else lt=t,t=s;return vt[c]={nextPos:lt,result:t},t}function St(){var t,r,n,u,o,a,c,i=36*lt+8,l=vt[i];if(l)return lt=l.nextPos,l.result;if(t=lt,33===e.charCodeAt(lt)?(r="!",lt++):(r=s,gt(x)),r===s&&(r=null),r!==s){if(n=[],(u=kt())!==s)for(;u!==s;)n.push(u),u=kt();else n=s;n!==s?(o=r,c=1===(a=n).length?a[0]:{type:"compound",selectors:a},o&&(c.subject=!0),t=r=c):(lt=t,t=s)}else lt=t,t=s;return vt[i]={nextPos:lt,result:t},t}function kt(){var t,r=36*lt+9,n=vt[r];return n?(lt=n.nextPos,n.result):((t=function(){var t,r,n=36*lt+10,u=vt[n];return u?(lt=u.nextPos,u.result):(42===e.charCodeAt(lt)?(r="*",lt++):(r=s,gt(g)),r!==s&&(r={type:"wildcard",value:r}),t=r,vt[n]={nextPos:lt,result:t},t)}())===s&&(t=function(){var t,r,n,u=36*lt+11,o=vt[u];return o?(lt=o.nextPos,o.result):(t=lt,35===e.charCodeAt(lt)?(r="#",lt++):(r=s,gt(P)),r===s&&(r=null),r!==s&&(n=bt())!==s?t=r={type:"identifier",value:n}:(lt=t,t=s),vt[u]={nextPos:lt,result:t},t)}())===s&&(t=function(){var t,r,n,u,o=36*lt+12,a=vt[o];return a?(lt=a.nextPos,a.result):(t=lt,91===e.charCodeAt(lt)?(r="[",lt++):(r=s,gt(m)),r!==s&&mt()!==s&&(n=function(){var t,r,n,u,o=36*lt+16,a=vt[o];return a?(lt=a.nextPos,a.result):(t=lt,(r=It())!==s&&mt()!==s&&(n=function(){var t,r,n,u=36*lt+14,o=vt[u];return o?(lt=o.nextPos,o.result):(t=lt,33===e.charCodeAt(lt)?(r="!",lt++):(r=s,gt(x)),r===s&&(r=null),r!==s?(61===e.charCodeAt(lt)?(n="=",lt++):(n=s,gt(j)),n!==s?(r=E(r),t=r):(lt=t,t=s)):(lt=t,t=s),vt[u]={nextPos:lt,result:t},t)}())!==s&&mt()!==s?((u=function(){var t,r,n,u,o,a=36*lt+20,c=vt[a];if(c)return lt=c.nextPos,c.result;if(t=lt,"type("===e.substr(lt,5)?(r="type(",lt+=5):(r=s,gt(N)),r!==s)if(mt()!==s){if(n=[],V.test(e.charAt(lt))?(u=e.charAt(lt),lt++):(u=s,gt(W)),u!==s)for(;u!==s;)n.push(u),V.test(e.charAt(lt))?(u=e.charAt(lt),lt++):(u=s,gt(W));else n=s;n!==s&&(u=mt())!==s?(41===e.charCodeAt(lt)?(o=")",lt++):(o=s,gt($)),o!==s?(r={type:"type",value:n.join("")},t=r):(lt=t,t=s)):(lt=t,t=s)}else lt=t,t=s;else lt=t,t=s;return vt[a]={nextPos:lt,result:t},t}())===s&&(u=function(){var t,r,n,u,o,a,c=36*lt+22,i=vt[c];if(i)return lt=i.nextPos,i.result;if(t=lt,47===e.charCodeAt(lt)?(r="/",lt++):(r=s,gt(J)),r!==s){if(n=[],(u=Tt())===s&&(u=Ft())===s&&(u=Kt()),u!==s)for(;u!==s;)n.push(u),(u=Tt())===s&&(u=Ft())===s&&(u=Kt());else n=s;n!==s?(47===e.charCodeAt(lt)?(u="/",lt++):(u=s,gt(J)),u!==s?((o=function(){var t,r,n=36*lt+21,u=vt[n];if(u)return lt=u.nextPos,u.result;if(t=[],z.test(e.charAt(lt))?(r=e.charAt(lt),lt++):(r=s,gt(B)),r!==s)for(;r!==s;)t.push(r),z.test(e.charAt(lt))?(r=e.charAt(lt),lt++):(r=s,gt(B));else t=s;return vt[n]={nextPos:lt,result:t},t}())===s&&(o=null),o!==s?(a=o,r={type:"regexp",value:new RegExp(n.join(""),a?a.join(""):"")},t=r):(lt=t,t=s)):(lt=t,t=s)):(lt=t,t=s)}else lt=t,t=s;return vt[c]={nextPos:lt,result:t},t}()),u!==s?(r=T(r,n,u),t=r):(lt=t,t=s)):(lt=t,t=s),t===s&&(t=lt,(r=It())!==s&&mt()!==s&&(n=function(){var t,r,n,u=36*lt+13,o=vt[u];return o?(lt=o.nextPos,o.result):(t=lt,C.test(e.charAt(lt))?(r=e.charAt(lt),lt++):(r=s,gt(w)),r===s&&(r=null),r!==s?(61===e.charCodeAt(lt)?(n="=",lt++):(n=s,gt(j)),n!==s?(r=E(r),t=r):(lt=t,t=s)):(lt=t,t=s),t===s&&(S.test(e.charAt(lt))?(t=e.charAt(lt),lt++):(t=s,gt(k))),vt[u]={nextPos:lt,result:t},t)}())!==s&&mt()!==s?((u=function(){var t,r,n,u,o,a,c=36*lt+17,i=vt[c];if(i)return lt=i.nextPos,i.result;if(t=lt,34===e.charCodeAt(lt)?(r='"',lt++):(r=s,gt(F)),r!==s){for(n=[],K.test(e.charAt(lt))?(u=e.charAt(lt),lt++):(u=s,gt(D)),u===s&&(u=lt,92===e.charCodeAt(lt)?(o="\\",lt++):(o=s,gt(O)),o!==s?(e.length>lt?(a=e.charAt(lt),lt++):(a=s,gt(L)),a!==s?(o=R(o,a),u=o):(lt=u,u=s)):(lt=u,u=s));u!==s;)n.push(u),K.test(e.charAt(lt))?(u=e.charAt(lt),lt++):(u=s,gt(D)),u===s&&(u=lt,92===e.charCodeAt(lt)?(o="\\",lt++):(o=s,gt(O)),o!==s?(e.length>lt?(a=e.charAt(lt),lt++):(a=s,gt(L)),a!==s?(o=R(o,a),u=o):(lt=u,u=s)):(lt=u,u=s));n!==s?(34===e.charCodeAt(lt)?(u='"',lt++):(u=s,gt(F)),u!==s?(r=M(n),t=r):(lt=t,t=s)):(lt=t,t=s)}else lt=t,t=s;if(t===s)if(t=lt,39===e.charCodeAt(lt)?(r="'",lt++):(r=s,gt(U)),r!==s){for(n=[],_.test(e.charAt(lt))?(u=e.charAt(lt),lt++):(u=s,gt(q)),u===s&&(u=lt,92===e.charCodeAt(lt)?(o="\\",lt++):(o=s,gt(O)),o!==s?(e.length>lt?(a=e.charAt(lt),lt++):(a=s,gt(L)),a!==s?(o=R(o,a),u=o):(lt=u,u=s)):(lt=u,u=s));u!==s;)n.push(u),_.test(e.charAt(lt))?(u=e.charAt(lt),lt++):(u=s,gt(q)),u===s&&(u=lt,92===e.charCodeAt(lt)?(o="\\",lt++):(o=s,gt(O)),o!==s?(e.length>lt?(a=e.charAt(lt),lt++):(a=s,gt(L)),a!==s?(o=R(o,a),u=o):(lt=u,u=s)):(lt=u,u=s));n!==s?(39===e.charCodeAt(lt)?(u="'",lt++):(u=s,gt(U)),u!==s?(r=M(n),t=r):(lt=t,t=s)):(lt=t,t=s)}else lt=t,t=s;return vt[c]={nextPos:lt,result:t},t}())===s&&(u=function(){var t,r,n,u,o,a,c,i=36*lt+18,l=vt[i];if(l)return lt=l.nextPos,l.result;for(t=lt,r=lt,n=[],G.test(e.charAt(lt))?(u=e.charAt(lt),lt++):(u=s,gt(H));u!==s;)n.push(u),G.test(e.charAt(lt))?(u=e.charAt(lt),lt++):(u=s,gt(H));if(n!==s?(46===e.charCodeAt(lt)?(u=".",lt++):(u=s,gt(I)),u!==s?r=n=[n,u]:(lt=r,r=s)):(lt=r,r=s),r===s&&(r=null),r!==s){if(n=[],G.test(e.charAt(lt))?(u=e.charAt(lt),lt++):(u=s,gt(H)),u!==s)for(;u!==s;)n.push(u),G.test(e.charAt(lt))?(u=e.charAt(lt),lt++):(u=s,gt(H));else n=s;n!==s?(a=n,c=(o=r)?[].concat.apply([],o).join(""):"",r={type:"literal",value:parseFloat(c+a.join(""))},t=r):(lt=t,t=s)}else lt=t,t=s;return vt[i]={nextPos:lt,result:t},t}())===s&&(u=function(){var t,e,r=36*lt+19,n=vt[r];return n?(lt=n.nextPos,n.result):((e=bt())!==s&&(e={type:"literal",value:e}),t=e,vt[r]={nextPos:lt,result:t},t)}()),u!==s?(r=T(r,n,u),t=r):(lt=t,t=s)):(lt=t,t=s),t===s&&(t=lt,(r=It())!==s&&(r={type:"attribute",name:r}),t=r)),vt[o]={nextPos:lt,result:t},t)}())!==s&&mt()!==s?(93===e.charCodeAt(lt)?(u="]",lt++):(u=s,gt(b)),u!==s?t=r=n:(lt=t,t=s)):(lt=t,t=s),vt[o]={nextPos:lt,result:t},t)}())===s&&(t=function(){var t,r,n,u,o,a,c,i,l=36*lt+26,f=vt[l];if(f)return lt=f.nextPos,f.result;if(t=lt,46===e.charCodeAt(lt)?(r=".",lt++):(r=s,gt(I)),r!==s)if((n=bt())!==s){for(u=[],o=lt,46===e.charCodeAt(lt)?(a=".",lt++):(a=s,gt(I)),a!==s&&(c=bt())!==s?o=a=[a,c]:(lt=o,o=s);o!==s;)u.push(o),o=lt,46===e.charCodeAt(lt)?(a=".",lt++):(a=s,gt(I)),a!==s&&(c=bt())!==s?o=a=[a,c]:(lt=o,o=s);u!==s?(i=n,r={type:"field",name:u.reduce((function(t,e){return t+e[0]+e[1]}),i)},t=r):(lt=t,t=s)}else lt=t,t=s;else lt=t,t=s;return vt[l]={nextPos:lt,result:t},t}())===s&&(t=function(){var t,r,n,u,o=36*lt+27,a=vt[o];return a?(lt=a.nextPos,a.result):(t=lt,":not("===e.substr(lt,5)?(r=":not(",lt+=5):(r=s,gt(tt)),r!==s&&mt()!==s&&(n=wt())!==s&&mt()!==s?(41===e.charCodeAt(lt)?(u=")",lt++):(u=s,gt($)),u!==s?t=r={type:"not",selectors:n}:(lt=t,t=s)):(lt=t,t=s),vt[o]={nextPos:lt,result:t},t)}())===s&&(t=function(){var t,r,n,u,o=36*lt+28,a=vt[o];return a?(lt=a.nextPos,a.result):(t=lt,":matches("===e.substr(lt,9)?(r=":matches(",lt+=9):(r=s,gt(et)),r!==s&&mt()!==s&&(n=wt())!==s&&mt()!==s?(41===e.charCodeAt(lt)?(u=")",lt++):(u=s,gt($)),u!==s?(r=rt(n),t=r):(lt=t,t=s)):(lt=t,t=s),vt[o]={nextPos:lt,result:t},t)}())===s&&(t=function(){var t,r,n,u,o=36*lt+29,a=vt[o];return a?(lt=a.nextPos,a.result):(t=lt,":is("===e.substr(lt,4)?(r=":is(",lt+=4):(r=s,gt(nt)),r!==s&&mt()!==s&&(n=wt())!==s&&mt()!==s?(41===e.charCodeAt(lt)?(u=")",lt++):(u=s,gt($)),u!==s?(r=rt(n),t=r):(lt=t,t=s)):(lt=t,t=s),vt[o]={nextPos:lt,result:t},t)}())===s&&(t=function(){var t,r,n,u,o=36*lt+30,a=vt[o];return a?(lt=a.nextPos,a.result):(t=lt,":has("===e.substr(lt,5)?(r=":has(",lt+=5):(r=s,gt(ut)),r!==s&&mt()!==s&&(n=function(){var t,r,n,u,o,a,c,i,l=36*lt+4,f=vt[l];if(f)return lt=f.nextPos,f.result;if(t=lt,(r=jt())!==s){for(n=[],u=lt,(o=mt())!==s?(44===e.charCodeAt(lt)?(a=",",lt++):(a=s,gt(y)),a!==s&&(c=mt())!==s&&(i=jt())!==s?u=o=[o,a,c,i]:(lt=u,u=s)):(lt=u,u=s);u!==s;)n.push(u),u=lt,(o=mt())!==s?(44===e.charCodeAt(lt)?(a=",",lt++):(a=s,gt(y)),a!==s&&(c=mt())!==s&&(i=jt())!==s?u=o=[o,a,c,i]:(lt=u,u=s)):(lt=u,u=s);n!==s?t=r=A(r,n):(lt=t,t=s)}else lt=t,t=s;return vt[l]={nextPos:lt,result:t},t}())!==s&&mt()!==s?(41===e.charCodeAt(lt)?(u=")",lt++):(u=s,gt($)),u!==s?t=r={type:"has",selectors:n}:(lt=t,t=s)):(lt=t,t=s),vt[o]={nextPos:lt,result:t},t)}())===s&&(t=function(){var t,r,n=36*lt+31,u=vt[n];return u?(lt=u.nextPos,u.result):(":first-child"===e.substr(lt,12)?(r=":first-child",lt+=12):(r=s,gt(ot)),r!==s&&(r=Dt(1)),t=r,vt[n]={nextPos:lt,result:t},t)}())===s&&(t=function(){var t,r,n=36*lt+32,u=vt[n];return u?(lt=u.nextPos,u.result):(":last-child"===e.substr(lt,11)?(r=":last-child",lt+=11):(r=s,gt(at)),r!==s&&(r=Ot(1)),t=r,vt[n]={nextPos:lt,result:t},t)}())===s&&(t=function(){var t,r,n,u,o,a=36*lt+33,c=vt[a];if(c)return lt=c.nextPos,c.result;if(t=lt,":nth-child("===e.substr(lt,11)?(r=":nth-child(",lt+=11):(r=s,gt(st)),r!==s)if(mt()!==s){if(n=[],G.test(e.charAt(lt))?(u=e.charAt(lt),lt++):(u=s,gt(H)),u!==s)for(;u!==s;)n.push(u),G.test(e.charAt(lt))?(u=e.charAt(lt),lt++):(u=s,gt(H));else n=s;n!==s&&(u=mt())!==s?(41===e.charCodeAt(lt)?(o=")",lt++):(o=s,gt($)),o!==s?(r=Dt(parseInt(n.join(""),10)),t=r):(lt=t,t=s)):(lt=t,t=s)}else lt=t,t=s;else lt=t,t=s;return vt[a]={nextPos:lt,result:t},t}())===s&&(t=function(){var t,r,n,u,o,a=36*lt+34,c=vt[a];if(c)return lt=c.nextPos,c.result;if(t=lt,":nth-last-child("===e.substr(lt,16)?(r=":nth-last-child(",lt+=16):(r=s,gt(ct)),r!==s)if(mt()!==s){if(n=[],G.test(e.charAt(lt))?(u=e.charAt(lt),lt++):(u=s,gt(H)),u!==s)for(;u!==s;)n.push(u),G.test(e.charAt(lt))?(u=e.charAt(lt),lt++):(u=s,gt(H));else n=s;n!==s&&(u=mt())!==s?(41===e.charCodeAt(lt)?(o=")",lt++):(o=s,gt($)),o!==s?(r=Ot(parseInt(n.join(""),10)),t=r):(lt=t,t=s)):(lt=t,t=s)}else lt=t,t=s;else lt=t,t=s;return vt[a]={nextPos:lt,result:t},t}())===s&&(t=function(){var t,r,n,u=36*lt+35,o=vt[u];return o?(lt=o.nextPos,o.result):(t=lt,58===e.charCodeAt(lt)?(r=":",lt++):(r=s,gt(it)),r!==s&&(n=bt())!==s?t=r={type:"class",name:n}:(lt=t,t=s),vt[u]={nextPos:lt,result:t},t)}()),vt[r]={nextPos:lt,result:t},t)}function It(){var t,r,n,u,o,a,c,i,l=36*lt+15,f=vt[l];if(f)return lt=f.nextPos,f.result;if(t=lt,(r=bt())!==s){for(n=[],u=lt,46===e.charCodeAt(lt)?(o=".",lt++):(o=s,gt(I)),o!==s&&(a=bt())!==s?u=o=[o,a]:(lt=u,u=s);u!==s;)n.push(u),u=lt,46===e.charCodeAt(lt)?(o=".",lt++):(o=s,gt(I)),o!==s&&(a=bt())!==s?u=o=[o,a]:(lt=u,u=s);n!==s?(c=r,i=n,t=r=[].concat.apply([c],i).join("")):(lt=t,t=s)}else lt=t,t=s;return vt[l]={nextPos:lt,result:t},t}function Tt(){var t,r,n,u,o=36*lt+23,a=vt[o];if(a)return lt=a.nextPos,a.result;if(t=lt,91===e.charCodeAt(lt)?(r="[",lt++):(r=s,gt(m)),r!==s){if(n=[],Q.test(e.charAt(lt))?(u=e.charAt(lt),lt++):(u=s,gt(X)),u===s&&(u=Ft()),u!==s)for(;u!==s;)n.push(u),Q.test(e.charAt(lt))?(u=e.charAt(lt),lt++):(u=s,gt(X)),u===s&&(u=Ft());else n=s;n!==s?(93===e.charCodeAt(lt)?(u="]",lt++):(u=s,gt(b)),u!==s?t=r="["+n.join("")+"]":(lt=t,t=s)):(lt=t,t=s)}else lt=t,t=s;return vt[o]={nextPos:lt,result:t},t}function Ft(){var t,r,n,u=36*lt+24,o=vt[u];return o?(lt=o.nextPos,o.result):(t=lt,92===e.charCodeAt(lt)?(r="\\",lt++):(r=s,gt(O)),r!==s?(e.length>lt?(n=e.charAt(lt),lt++):(n=s,gt(L)),n!==s?t=r="\\"+n:(lt=t,t=s)):(lt=t,t=s),vt[u]={nextPos:lt,result:t},t)}function Kt(){var t,r,n,u=36*lt+25,o=vt[u];if(o)return lt=o.nextPos,o.result;if(r=[],Y.test(e.charAt(lt))?(n=e.charAt(lt),lt++):(n=s,gt(Z)),n!==s)for(;n!==s;)r.push(n),Y.test(e.charAt(lt))?(n=e.charAt(lt),lt++):(n=s,gt(Z));else r=s;return r!==s&&(r=r.join("")),t=r,vt[u]={nextPos:lt,result:t},t}function Dt(t){return{type:"nth-child",index:{type:"literal",value:t}}}function Ot(t){return{type:"nth-last-child",index:{type:"literal",value:t}}}if((n=i())!==s&<===e.length)return n;throw n!==s&<0&&h(t,e,r))&&f(e[0],e.slice(1),r)};case"descendant":var y=i(e.left),A=i(e.right);return function(t,e,r){if(A(t,e,r))for(var n=0,u=e.length;n":return function(t){return s(t,x)>e.value.value};case">=":return function(t){return s(t,x)>=e.value.value}}throw new Error("Unknown operator: ".concat(e.operator));case"sibling":var m=i(e.left),b=i(e.right);return function(t,r,n){return b(t,r,n)&&p(t,m,r,"LEFT_SIDE",n)||e.left.subject&&m(t,r,n)&&p(t,b,r,"RIGHT_SIDE",n)};case"adjacent":var C=i(e.left),w=i(e.right);return function(t,r,n){return w(t,r,n)&&v(t,C,r,"LEFT_SIDE",n)||e.right.subject&&C(t,r,n)&&v(t,w,r,"RIGHT_SIDE",n)};case"nth-child":var j=e.index.value,E=i(e.right);return function(t,e,r){return E(t,e,r)&&d(t,e,j,r)};case"nth-last-child":var S=-e.index.value,k=i(e.right);return function(t,e,r){return k(t,e,r)&&d(t,e,S,r)};case"class":var I=e.name.toLowerCase();return function(t,r,n){if(n&&n.matchClass)return n.matchClass(e.name,t,r);if(n&&n.nodeTypeKey)return!1;switch(I){case"statement":if("Statement"===t.type.slice(-9))return!0;case"declaration":return"Declaration"===t.type.slice(-11);case"pattern":if("Pattern"===t.type.slice(-7))return!0;case"expression":return"Expression"===t.type.slice(-10)||"Literal"===t.type.slice(-7)||"Identifier"===t.type&&(0===r.length||"MetaProperty"!==r[0].type)||"MetaProperty"===t.type;case"function":return"FunctionDeclaration"===t.type||"FunctionExpression"===t.type||"ArrowFunctionExpression"===t.type}throw new Error("Unknown class name: ".concat(e.name))}}throw new Error("Unknown selector type: ".concat(e.type))}function f(e,r){var n=r&&r.nodeTypeKey||"type",u=e[n];return r&&r.visitorKeys&&r.visitorKeys[u]?r.visitorKeys[u]:t.VisitorKeys[u]?t.VisitorKeys[u]:r&&"function"==typeof r.fallback?r.fallback(e):Object.keys(e).filter((function(t){return t!==n}))}function h(t,e){var r=e&&e.nodeTypeKey||"type";return null!==t&&"object"===u(t)&&"string"==typeof t[r]}function p(t,e,n,u,o){var a=r(n,1)[0];if(!a)return!1;for(var s=f(a,o),c=0;c0&&h(i[l-1],o)&&e(i[l-1],n,o))return!0;if("RIGHT_SIDE"===u&&l=0&&i 0) {\n for (i = 1, j = 1; i < descriptions.length; i++) {\n if (descriptions[i - 1] !== descriptions[i]) {\n descriptions[j] = descriptions[i];\n j++;\n }\n }\n descriptions.length = j;\n }\n\n switch (descriptions.length) {\n case 1:\n return descriptions[0];\n\n case 2:\n return descriptions[0] + \" or \" + descriptions[1];\n\n default:\n return descriptions.slice(0, -1).join(\", \")\n + \", or \"\n + descriptions[descriptions.length - 1];\n }\n }\n\n function describeFound(found) {\n return found ? \"\\\"\" + literalEscape(found) + \"\\\"\" : \"end of input\";\n }\n\n return \"Expected \" + describeExpected(expected) + \" but \" + describeFound(found) + \" found.\";\n };\n\n function peg$parse(input, options) {\n options = options !== void 0 ? options : {};\n\n var peg$FAILED = {},\n\n peg$startRuleFunctions = { start: peg$parsestart },\n peg$startRuleFunction = peg$parsestart,\n\n peg$c0 = function(ss) {\n return ss.length === 1 ? ss[0] : { type: 'matches', selectors: ss };\n },\n peg$c1 = function() { return void 0; },\n peg$c2 = \" \",\n peg$c3 = peg$literalExpectation(\" \", false),\n peg$c4 = /^[^ [\\],():#!=><~+.]/,\n peg$c5 = peg$classExpectation([\" \", \"[\", \"]\", \",\", \"(\", \")\", \":\", \"#\", \"!\", \"=\", \">\", \"<\", \"~\", \"+\", \".\"], true, false),\n peg$c6 = function(i) { return i.join(''); },\n peg$c7 = \">\",\n peg$c8 = peg$literalExpectation(\">\", false),\n peg$c9 = function() { return 'child'; },\n peg$c10 = \"~\",\n peg$c11 = peg$literalExpectation(\"~\", false),\n peg$c12 = function() { return 'sibling'; },\n peg$c13 = \"+\",\n peg$c14 = peg$literalExpectation(\"+\", false),\n peg$c15 = function() { return 'adjacent'; },\n peg$c16 = function() { return 'descendant'; },\n peg$c17 = \",\",\n peg$c18 = peg$literalExpectation(\",\", false),\n peg$c19 = function(s, ss) {\n return [s].concat(ss.map(function (s) { return s[3]; }));\n },\n peg$c20 = function(op, s) {\n if (!op) return s;\n return { type: op, left: { type: 'exactNode' }, right: s };\n },\n peg$c21 = function(a, ops) {\n return ops.reduce(function (memo, rhs) {\n return { type: rhs[0], left: memo, right: rhs[1] };\n }, a);\n },\n peg$c22 = \"!\",\n peg$c23 = peg$literalExpectation(\"!\", false),\n peg$c24 = function(subject, as) {\n const b = as.length === 1 ? as[0] : { type: 'compound', selectors: as };\n if(subject) b.subject = true;\n return b;\n },\n peg$c25 = \"*\",\n peg$c26 = peg$literalExpectation(\"*\", false),\n peg$c27 = function(a) { return { type: 'wildcard', value: a }; },\n peg$c28 = \"#\",\n peg$c29 = peg$literalExpectation(\"#\", false),\n peg$c30 = function(i) { return { type: 'identifier', value: i }; },\n peg$c31 = \"[\",\n peg$c32 = peg$literalExpectation(\"[\", false),\n peg$c33 = \"]\",\n peg$c34 = peg$literalExpectation(\"]\", false),\n peg$c35 = function(v) { return v; },\n peg$c36 = /^[>\", \"<\", \"!\"], false, false),\n peg$c38 = \"=\",\n peg$c39 = peg$literalExpectation(\"=\", false),\n peg$c40 = function(a) { return (a || '') + '='; },\n peg$c41 = /^[><]/,\n peg$c42 = peg$classExpectation([\">\", \"<\"], false, false),\n peg$c43 = \".\",\n peg$c44 = peg$literalExpectation(\".\", false),\n peg$c45 = function(a, as) {\n return [].concat.apply([a], as).join('');\n },\n peg$c46 = function(name, op, value) {\n return { type: 'attribute', name: name, operator: op, value: value };\n },\n peg$c47 = function(name) { return { type: 'attribute', name: name }; },\n peg$c48 = \"\\\"\",\n peg$c49 = peg$literalExpectation(\"\\\"\", false),\n peg$c50 = /^[^\\\\\"]/,\n peg$c51 = peg$classExpectation([\"\\\\\", \"\\\"\"], true, false),\n peg$c52 = \"\\\\\",\n peg$c53 = peg$literalExpectation(\"\\\\\", false),\n peg$c54 = peg$anyExpectation(),\n peg$c55 = function(a, b) { return a + b; },\n peg$c56 = function(d) {\n return { type: 'literal', value: strUnescape(d.join('')) };\n },\n peg$c57 = \"'\",\n peg$c58 = peg$literalExpectation(\"'\", false),\n peg$c59 = /^[^\\\\']/,\n peg$c60 = peg$classExpectation([\"\\\\\", \"'\"], true, false),\n peg$c61 = /^[0-9]/,\n peg$c62 = peg$classExpectation([[\"0\", \"9\"]], false, false),\n peg$c63 = function(a, b) {\n // Can use `a.flat().join('')` once supported\n const leadingDecimals = a ? [].concat.apply([], a).join('') : '';\n return { type: 'literal', value: parseFloat(leadingDecimals + b.join('')) };\n },\n peg$c64 = function(i) { return { type: 'literal', value: i }; },\n peg$c65 = \"type(\",\n peg$c66 = peg$literalExpectation(\"type(\", false),\n peg$c67 = /^[^ )]/,\n peg$c68 = peg$classExpectation([\" \", \")\"], true, false),\n peg$c69 = \")\",\n peg$c70 = peg$literalExpectation(\")\", false),\n peg$c71 = function(t) { return { type: 'type', value: t.join('') }; },\n peg$c72 = /^[imsu]/,\n peg$c73 = peg$classExpectation([\"i\", \"m\", \"s\", \"u\"], false, false),\n peg$c74 = \"/\",\n peg$c75 = peg$literalExpectation(\"/\", false),\n peg$c76 = function(pattern, flgs) {\n return {\n type: 'regexp', value: new RegExp(pattern.join(''), flgs ? flgs.join('') : '')\n };\n },\n peg$c77 = /^[^\\]\\\\]/,\n peg$c78 = peg$classExpectation([\"]\", \"\\\\\"], true, false),\n peg$c79 = function(cs) { return '[' + cs.join('') + ']'; },\n peg$c80 = function(a) { return '\\\\' + a; },\n peg$c81 = /^[^\\/\\\\[]/,\n peg$c82 = peg$classExpectation([\"/\", \"\\\\\", \"[\"], true, false),\n peg$c83 = function(cs) { return cs.join(''); },\n peg$c84 = function(i, is) {\n return { type: 'field', name: is.reduce(function(memo, p){ return memo + p[0] + p[1]; }, i)};\n },\n peg$c85 = \":not(\",\n peg$c86 = peg$literalExpectation(\":not(\", false),\n peg$c87 = function(ss) { return { type: 'not', selectors: ss }; },\n peg$c88 = \":matches(\",\n peg$c89 = peg$literalExpectation(\":matches(\", false),\n peg$c90 = function(ss) { return { type: 'matches', selectors: ss }; },\n peg$c91 = \":is(\",\n peg$c92 = peg$literalExpectation(\":is(\", false),\n peg$c93 = \":has(\",\n peg$c94 = peg$literalExpectation(\":has(\", false),\n peg$c95 = function(ss) { return { type: 'has', selectors: ss }; },\n peg$c96 = \":first-child\",\n peg$c97 = peg$literalExpectation(\":first-child\", false),\n peg$c98 = function() { return nth(1); },\n peg$c99 = \":last-child\",\n peg$c100 = peg$literalExpectation(\":last-child\", false),\n peg$c101 = function() { return nthLast(1); },\n peg$c102 = \":nth-child(\",\n peg$c103 = peg$literalExpectation(\":nth-child(\", false),\n peg$c104 = function(n) { return nth(parseInt(n.join(''), 10)); },\n peg$c105 = \":nth-last-child(\",\n peg$c106 = peg$literalExpectation(\":nth-last-child(\", false),\n peg$c107 = function(n) { return nthLast(parseInt(n.join(''), 10)); },\n peg$c108 = \":\",\n peg$c109 = peg$literalExpectation(\":\", false),\n peg$c110 = function(c) {\n return { type: 'class', name: c };\n },\n\n peg$currPos = 0,\n peg$savedPos = 0,\n peg$posDetailsCache = [{ line: 1, column: 1 }],\n peg$maxFailPos = 0,\n peg$maxFailExpected = [],\n peg$silentFails = 0,\n\n peg$resultsCache = {},\n\n peg$result;\n\n if (\"startRule\" in options) {\n if (!(options.startRule in peg$startRuleFunctions)) {\n throw new Error(\"Can't start parsing from rule \\\"\" + options.startRule + \"\\\".\");\n }\n\n peg$startRuleFunction = peg$startRuleFunctions[options.startRule];\n }\n\n function text() {\n return input.substring(peg$savedPos, peg$currPos);\n }\n\n function location() {\n return peg$computeLocation(peg$savedPos, peg$currPos);\n }\n\n function expected(description, location) {\n location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos)\n\n throw peg$buildStructuredError(\n [peg$otherExpectation(description)],\n input.substring(peg$savedPos, peg$currPos),\n location\n );\n }\n\n function error(message, location) {\n location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos)\n\n throw peg$buildSimpleError(message, location);\n }\n\n function peg$literalExpectation(text, ignoreCase) {\n return { type: \"literal\", text: text, ignoreCase: ignoreCase };\n }\n\n function peg$classExpectation(parts, inverted, ignoreCase) {\n return { type: \"class\", parts: parts, inverted: inverted, ignoreCase: ignoreCase };\n }\n\n function peg$anyExpectation() {\n return { type: \"any\" };\n }\n\n function peg$endExpectation() {\n return { type: \"end\" };\n }\n\n function peg$otherExpectation(description) {\n return { type: \"other\", description: description };\n }\n\n function peg$computePosDetails(pos) {\n var details = peg$posDetailsCache[pos], p;\n\n if (details) {\n return details;\n } else {\n p = pos - 1;\n while (!peg$posDetailsCache[p]) {\n p--;\n }\n\n details = peg$posDetailsCache[p];\n details = {\n line: details.line,\n column: details.column\n };\n\n while (p < pos) {\n if (input.charCodeAt(p) === 10) {\n details.line++;\n details.column = 1;\n } else {\n details.column++;\n }\n\n p++;\n }\n\n peg$posDetailsCache[pos] = details;\n return details;\n }\n }\n\n function peg$computeLocation(startPos, endPos) {\n var startPosDetails = peg$computePosDetails(startPos),\n endPosDetails = peg$computePosDetails(endPos);\n\n return {\n start: {\n offset: startPos,\n line: startPosDetails.line,\n column: startPosDetails.column\n },\n end: {\n offset: endPos,\n line: endPosDetails.line,\n column: endPosDetails.column\n }\n };\n }\n\n function peg$fail(expected) {\n if (peg$currPos < peg$maxFailPos) { return; }\n\n if (peg$currPos > peg$maxFailPos) {\n peg$maxFailPos = peg$currPos;\n peg$maxFailExpected = [];\n }\n\n peg$maxFailExpected.push(expected);\n }\n\n function peg$buildSimpleError(message, location) {\n return new peg$SyntaxError(message, null, null, location);\n }\n\n function peg$buildStructuredError(expected, found, location) {\n return new peg$SyntaxError(\n peg$SyntaxError.buildMessage(expected, found),\n expected,\n found,\n location\n );\n }\n\n function peg$parsestart() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 36 + 0,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n s2 = peg$parseselectors();\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c0(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c1();\n }\n s0 = s1;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parse_() {\n var s0, s1;\n\n var key = peg$currPos * 36 + 1,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = [];\n if (input.charCodeAt(peg$currPos) === 32) {\n s1 = peg$c2;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c3); }\n }\n while (s1 !== peg$FAILED) {\n s0.push(s1);\n if (input.charCodeAt(peg$currPos) === 32) {\n s1 = peg$c2;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c3); }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseidentifierName() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 2,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = [];\n if (peg$c4.test(input.charAt(peg$currPos))) {\n s2 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c5); }\n }\n if (s2 !== peg$FAILED) {\n while (s2 !== peg$FAILED) {\n s1.push(s2);\n if (peg$c4.test(input.charAt(peg$currPos))) {\n s2 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c5); }\n }\n }\n } else {\n s1 = peg$FAILED;\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c6(s1);\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsebinaryOp() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 36 + 3,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 62) {\n s2 = peg$c7;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c8); }\n }\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c9();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 126) {\n s2 = peg$c10;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c11); }\n }\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c12();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 43) {\n s2 = peg$c13;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c14); }\n }\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c15();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 32) {\n s1 = peg$c2;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c3); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c16();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsehasSelectors() {\n var s0, s1, s2, s3, s4, s5, s6, s7;\n\n var key = peg$currPos * 36 + 4,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parsehasSelector();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parsehasSelector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parsehasSelector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c19(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseselectors() {\n var s0, s1, s2, s3, s4, s5, s6, s7;\n\n var key = peg$currPos * 36 + 5,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseselector();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parseselector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parseselector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c19(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsehasSelector() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 6,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parsebinaryOp();\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseselector();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c20(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseselector() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 7,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parsesequence();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n s4 = peg$parsebinaryOp();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsesequence();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n s4 = peg$parsebinaryOp();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsesequence();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c21(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsesequence() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 36 + 8,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 33) {\n s1 = peg$c22;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c23); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$parseatom();\n if (s3 !== peg$FAILED) {\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$parseatom();\n }\n } else {\n s2 = peg$FAILED;\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c24(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseatom() {\n var s0;\n\n var key = peg$currPos * 36 + 9,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$parsewildcard();\n if (s0 === peg$FAILED) {\n s0 = peg$parseidentifier();\n if (s0 === peg$FAILED) {\n s0 = peg$parseattr();\n if (s0 === peg$FAILED) {\n s0 = peg$parsefield();\n if (s0 === peg$FAILED) {\n s0 = peg$parsenegation();\n if (s0 === peg$FAILED) {\n s0 = peg$parsematches();\n if (s0 === peg$FAILED) {\n s0 = peg$parseis();\n if (s0 === peg$FAILED) {\n s0 = peg$parsehas();\n if (s0 === peg$FAILED) {\n s0 = peg$parsefirstChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parselastChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parsenthChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parsenthLastChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parseclass();\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsewildcard() {\n var s0, s1;\n\n var key = peg$currPos * 36 + 10,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 42) {\n s1 = peg$c25;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c26); }\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c27(s1);\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseidentifier() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 11,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 35) {\n s1 = peg$c28;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c29); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseidentifierName();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c30(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattr() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 12,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 91) {\n s1 = peg$c31;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c32); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseattrValue();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 93) {\n s5 = peg$c33;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c34); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c35(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrOps() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 13,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (peg$c36.test(input.charAt(peg$currPos))) {\n s1 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c37); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 61) {\n s2 = peg$c38;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c39); }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c40(s1);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n if (peg$c41.test(input.charAt(peg$currPos))) {\n s0 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s0 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c42); }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrEqOps() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 14,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 33) {\n s1 = peg$c22;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c23); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 61) {\n s2 = peg$c38;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c39); }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c40(s1);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrName() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 15,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseidentifierName();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s4 = peg$c43;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s4 !== peg$FAILED) {\n s5 = peg$parseidentifierName();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s4 = peg$c43;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s4 !== peg$FAILED) {\n s5 = peg$parseidentifierName();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c45(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrValue() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 16,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseattrName();\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseattrEqOps();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsetype();\n if (s5 === peg$FAILED) {\n s5 = peg$parseregex();\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c46(s1, s3, s5);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parseattrName();\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseattrOps();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsestring();\n if (s5 === peg$FAILED) {\n s5 = peg$parsenumber();\n if (s5 === peg$FAILED) {\n s5 = peg$parsepath();\n }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c46(s1, s3, s5);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parseattrName();\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c47(s1);\n }\n s0 = s1;\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsestring() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 17,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 34) {\n s1 = peg$c48;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c49); }\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c50.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c51); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c50.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c51); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 34) {\n s3 = peg$c48;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c49); }\n }\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c56(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 39) {\n s1 = peg$c57;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c58); }\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c59.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c60); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c59.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c60); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 39) {\n s3 = peg$c57;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c58); }\n }\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c56(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenumber() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 36 + 18,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$currPos;\n s2 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 46) {\n s3 = peg$c43;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s3 !== peg$FAILED) {\n s2 = [s2, s3];\n s1 = s2;\n } else {\n peg$currPos = s1;\n s1 = peg$FAILED;\n }\n } else {\n peg$currPos = s1;\n s1 = peg$FAILED;\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n if (s3 !== peg$FAILED) {\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n } else {\n s2 = peg$FAILED;\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c63(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsepath() {\n var s0, s1;\n\n var key = peg$currPos * 36 + 19,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseidentifierName();\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c64(s1);\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsetype() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 20,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 5) === peg$c65) {\n s1 = peg$c65;\n peg$currPos += 5;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c66); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = [];\n if (peg$c67.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c68); }\n }\n if (s4 !== peg$FAILED) {\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n if (peg$c67.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c68); }\n }\n }\n } else {\n s3 = peg$FAILED;\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c71(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseflags() {\n var s0, s1;\n\n var key = peg$currPos * 36 + 21,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = [];\n if (peg$c72.test(input.charAt(peg$currPos))) {\n s1 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c73); }\n }\n if (s1 !== peg$FAILED) {\n while (s1 !== peg$FAILED) {\n s0.push(s1);\n if (peg$c72.test(input.charAt(peg$currPos))) {\n s1 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c73); }\n }\n }\n } else {\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseregex() {\n var s0, s1, s2, s3, s4;\n\n var key = peg$currPos * 36 + 22,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 47) {\n s1 = peg$c74;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c75); }\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$parsere_character_class();\n if (s3 === peg$FAILED) {\n s3 = peg$parsere_escape();\n if (s3 === peg$FAILED) {\n s3 = peg$parsere_chars();\n }\n }\n if (s3 !== peg$FAILED) {\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$parsere_character_class();\n if (s3 === peg$FAILED) {\n s3 = peg$parsere_escape();\n if (s3 === peg$FAILED) {\n s3 = peg$parsere_chars();\n }\n }\n }\n } else {\n s2 = peg$FAILED;\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 47) {\n s3 = peg$c74;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c75); }\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parseflags();\n if (s4 === peg$FAILED) {\n s4 = null;\n }\n if (s4 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c76(s2, s4);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsere_character_class() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 36 + 23,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 91) {\n s1 = peg$c31;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c32); }\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c77.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c78); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$parsere_escape();\n }\n if (s3 !== peg$FAILED) {\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c77.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c78); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$parsere_escape();\n }\n }\n } else {\n s2 = peg$FAILED;\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 93) {\n s3 = peg$c33;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c34); }\n }\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c79(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsere_escape() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 24,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s1 = peg$c52;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s1 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s2 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c80(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsere_chars() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 25,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = [];\n if (peg$c81.test(input.charAt(peg$currPos))) {\n s2 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c82); }\n }\n if (s2 !== peg$FAILED) {\n while (s2 !== peg$FAILED) {\n s1.push(s2);\n if (peg$c81.test(input.charAt(peg$currPos))) {\n s2 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c82); }\n }\n }\n } else {\n s1 = peg$FAILED;\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c83(s1);\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsefield() {\n var s0, s1, s2, s3, s4, s5, s6;\n\n var key = peg$currPos * 36 + 26,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s1 = peg$c43;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseidentifierName();\n if (s2 !== peg$FAILED) {\n s3 = [];\n s4 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s5 = peg$c43;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parseidentifierName();\n if (s6 !== peg$FAILED) {\n s5 = [s5, s6];\n s4 = s5;\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n s4 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s5 = peg$c43;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parseidentifierName();\n if (s6 !== peg$FAILED) {\n s5 = [s5, s6];\n s4 = s5;\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n }\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c84(s2, s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenegation() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 27,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 5) === peg$c85) {\n s1 = peg$c85;\n peg$currPos += 5;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c86); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseselectors();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c87(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsematches() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 28,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 9) === peg$c88) {\n s1 = peg$c88;\n peg$currPos += 9;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c89); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseselectors();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c90(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseis() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 29,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 4) === peg$c91) {\n s1 = peg$c91;\n peg$currPos += 4;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c92); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseselectors();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c90(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsehas() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 30,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 5) === peg$c93) {\n s1 = peg$c93;\n peg$currPos += 5;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c94); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parsehasSelectors();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c95(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsefirstChild() {\n var s0, s1;\n\n var key = peg$currPos * 36 + 31,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 12) === peg$c96) {\n s1 = peg$c96;\n peg$currPos += 12;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c97); }\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c98();\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parselastChild() {\n var s0, s1;\n\n var key = peg$currPos * 36 + 32,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 11) === peg$c99) {\n s1 = peg$c99;\n peg$currPos += 11;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c100); }\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c101();\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenthChild() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 33,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 11) === peg$c102) {\n s1 = peg$c102;\n peg$currPos += 11;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c103); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n if (s4 !== peg$FAILED) {\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n } else {\n s3 = peg$FAILED;\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c104(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenthLastChild() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 34,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 16) === peg$c105) {\n s1 = peg$c105;\n peg$currPos += 16;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c106); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n if (s4 !== peg$FAILED) {\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n } else {\n s3 = peg$FAILED;\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c107(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseclass() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 35,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 58) {\n s1 = peg$c108;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c109); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseidentifierName();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c110(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n\n function nth(n) { return { type: 'nth-child', index: { type: 'literal', value: n } }; }\n function nthLast(n) { return { type: 'nth-last-child', index: { type: 'literal', value: n } }; }\n function strUnescape(s) {\n return s.replace(/\\\\(.)/g, function(match, ch) {\n switch(ch) {\n case 'b': return '\\b';\n case 'f': return '\\f';\n case 'n': return '\\n';\n case 'r': return '\\r';\n case 't': return '\\t';\n case 'v': return '\\v';\n default: return ch;\n }\n });\n }\n\n\n peg$result = peg$startRuleFunction();\n\n if (peg$result !== peg$FAILED && peg$currPos === input.length) {\n return peg$result;\n } else {\n if (peg$result !== peg$FAILED && peg$currPos < input.length) {\n peg$fail(peg$endExpectation());\n }\n\n throw peg$buildStructuredError(\n peg$maxFailExpected,\n peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null,\n peg$maxFailPos < input.length\n ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1)\n : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)\n );\n }\n }\n\n return {\n SyntaxError: peg$SyntaxError,\n parse: peg$parse\n };\n});\n","/* vim: set sw=4 sts=4 : */\nimport estraverse from 'estraverse';\nimport parser from './parser.js';\n\n/**\n* @typedef {\"LEFT_SIDE\"|\"RIGHT_SIDE\"} Side\n*/\n\nconst LEFT_SIDE = 'LEFT_SIDE';\nconst RIGHT_SIDE = 'RIGHT_SIDE';\n\n/**\n * @external AST\n * @see https://esprima.readthedocs.io/en/latest/syntax-tree-format.html\n */\n\n/**\n * One of the rules of `grammar.pegjs`\n * @typedef {PlainObject} SelectorAST\n * @see grammar.pegjs\n*/\n\n/**\n * The `sequence` production of `grammar.pegjs`\n * @typedef {PlainObject} SelectorSequenceAST\n*/\n\n/**\n * Get the value of a property which may be multiple levels down\n * in the object.\n * @param {?PlainObject} obj\n * @param {string[]} keys\n * @returns {undefined|boolean|string|number|external:AST}\n */\nfunction getPath(obj, keys) {\n for (let i = 0; i < keys.length; ++i) {\n if (obj == null) { return obj; }\n obj = obj[keys[i]];\n }\n return obj;\n}\n\n/**\n * Determine whether `node` can be reached by following `path`,\n * starting at `ancestor`.\n * @param {?external:AST} node\n * @param {?external:AST} ancestor\n * @param {string[]} path\n * @param {Integer} fromPathIndex\n * @returns {boolean}\n */\nfunction inPath(node, ancestor, path, fromPathIndex) {\n let current = ancestor;\n for (let i = fromPathIndex; i < path.length; ++i) {\n if (current == null) {\n return false;\n }\n const field = current[path[i]];\n if (Array.isArray(field)) {\n for (let k = 0; k < field.length; ++k) {\n if (inPath(node, field[k], path, i + 1)) {\n return true;\n }\n }\n return false;\n }\n current = field;\n }\n return node === current;\n}\n\n/**\n * A generated matcher function for a selector.\n * @callback SelectorMatcher\n * @param {?SelectorAST} selector\n * @param {external:AST[]} [ancestry=[]]\n * @param {ESQueryOptions} [options]\n * @returns {void}\n*/\n\n/**\n * A WeakMap for holding cached matcher functions for selectors.\n * @type {WeakMap}\n*/\nconst MATCHER_CACHE = typeof WeakMap === 'function' ? new WeakMap : null;\n\n/**\n * Look up a matcher function for `selector` in the cache.\n * If it does not exist, generate it with `generateMatcher` and add it to the cache.\n * In engines without WeakMap, the caching is skipped and matchers are generated with every call.\n * @param {?SelectorAST} selector\n * @returns {SelectorMatcher}\n */\nfunction getMatcher(selector) {\n if (selector == null) {\n return () => true;\n }\n\n if (MATCHER_CACHE != null) {\n let matcher = MATCHER_CACHE.get(selector);\n if (matcher != null) {\n return matcher;\n }\n matcher = generateMatcher(selector);\n MATCHER_CACHE.set(selector, matcher);\n return matcher;\n }\n\n return generateMatcher(selector);\n}\n\n/**\n * Create a matcher function for `selector`,\n * @param {?SelectorAST} selector\n * @returns {SelectorMatcher}\n */\nfunction generateMatcher(selector) {\n switch(selector.type) {\n case 'wildcard':\n return () => true;\n\n case 'identifier': {\n const value = selector.value.toLowerCase();\n return (node, ancestry, options) => {\n const nodeTypeKey = (options && options.nodeTypeKey) || 'type';\n return value === node[nodeTypeKey].toLowerCase();\n };\n }\n\n case 'exactNode':\n return (node, ancestry) => {\n return ancestry.length === 0;\n };\n\n case 'field': {\n const path = selector.name.split('.');\n return (node, ancestry) => {\n const ancestor = ancestry[path.length - 1];\n return inPath(node, ancestor, path, 0);\n };\n }\n\n case 'matches': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n for (let i = 0; i < matchers.length; ++i) {\n if (matchers[i](node, ancestry, options)) { return true; }\n }\n return false;\n };\n }\n\n case 'compound': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n for (let i = 0; i < matchers.length; ++i) {\n if (!matchers[i](node, ancestry, options)) { return false; }\n }\n return true;\n };\n }\n\n case 'not': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n for (let i = 0; i < matchers.length; ++i) {\n if (matchers[i](node, ancestry, options)) { return false; }\n }\n return true;\n };\n }\n\n case 'has': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n let result = false;\n\n const a = [];\n estraverse.traverse(node, {\n enter (node, parent) {\n if (parent != null) { a.unshift(parent); }\n\n for (let i = 0; i < matchers.length; ++i) {\n if (matchers[i](node, a, options)) {\n result = true;\n this.break();\n return;\n }\n }\n },\n leave () { a.shift(); },\n keys: options && options.visitorKeys,\n fallback: options && options.fallback || 'iteration'\n });\n\n return result;\n };\n }\n\n case 'child': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) => {\n if (ancestry.length > 0 && right(node, ancestry, options)) {\n return left(ancestry[0], ancestry.slice(1), options);\n }\n return false;\n };\n }\n\n case 'descendant': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) => {\n if (right(node, ancestry, options)) {\n for (let i = 0, l = ancestry.length; i < l; ++i) {\n if (left(ancestry[i], ancestry.slice(i + 1), options)) {\n return true;\n }\n }\n }\n return false;\n };\n }\n\n case 'attribute': {\n const path = selector.name.split('.');\n switch (selector.operator) {\n case void 0:\n return (node) => getPath(node, path) != null;\n case '=':\n switch (selector.value.type) {\n case 'regexp':\n return (node) => {\n const p = getPath(node, path);\n return typeof p === 'string' && selector.value.value.test(p);\n };\n case 'literal': {\n const literal = `${selector.value.value}`;\n return (node) => literal === `${getPath(node, path)}`;\n }\n case 'type':\n return (node) => selector.value.value === typeof getPath(node, path);\n }\n throw new Error(`Unknown selector value type: ${selector.value.type}`);\n case '!=':\n switch (selector.value.type) {\n case 'regexp':\n return (node) => !selector.value.value.test(getPath(node, path));\n case 'literal': {\n const literal = `${selector.value.value}`;\n return (node) => literal !== `${getPath(node, path)}`;\n }\n case 'type':\n return (node) => selector.value.value !== typeof getPath(node, path);\n }\n throw new Error(`Unknown selector value type: ${selector.value.type}`);\n case '<=':\n return (node) => getPath(node, path) <= selector.value.value;\n case '<':\n return (node) => getPath(node, path) < selector.value.value;\n case '>':\n return (node) => getPath(node, path) > selector.value.value;\n case '>=':\n return (node) => getPath(node, path) >= selector.value.value;\n }\n throw new Error(`Unknown operator: ${selector.operator}`);\n }\n\n case 'sibling': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n sibling(node, left, ancestry, LEFT_SIDE, options) ||\n selector.left.subject &&\n left(node, ancestry, options) &&\n sibling(node, right, ancestry, RIGHT_SIDE, options);\n }\n\n case 'adjacent': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n adjacent(node, left, ancestry, LEFT_SIDE, options) ||\n selector.right.subject &&\n left(node, ancestry, options) &&\n adjacent(node, right, ancestry, RIGHT_SIDE, options);\n }\n\n case 'nth-child': {\n const nth = selector.index.value;\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n nthChild(node, ancestry, nth, options);\n }\n\n case 'nth-last-child': {\n const nth = -selector.index.value;\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n nthChild(node, ancestry, nth, options);\n }\n\n case 'class': {\n \n const name = selector.name.toLowerCase();\n\n return (node, ancestry, options) => {\n \n if (options && options.matchClass) {\n return options.matchClass(selector.name, node, ancestry);\n }\n \n if (options && options.nodeTypeKey) return false; \n\n switch(name){\n case 'statement':\n if(node.type.slice(-9) === 'Statement') return true;\n // fallthrough: interface Declaration <: Statement { }\n case 'declaration':\n return node.type.slice(-11) === 'Declaration';\n case 'pattern':\n if(node.type.slice(-7) === 'Pattern') return true;\n // fallthrough: interface Expression <: Node, Pattern { }\n case 'expression':\n return node.type.slice(-10) === 'Expression' ||\n node.type.slice(-7) === 'Literal' ||\n (\n node.type === 'Identifier' &&\n (ancestry.length === 0 || ancestry[0].type !== 'MetaProperty')\n ) ||\n node.type === 'MetaProperty';\n case 'function':\n return node.type === 'FunctionDeclaration' ||\n node.type === 'FunctionExpression' ||\n node.type === 'ArrowFunctionExpression';\n }\n throw new Error(`Unknown class name: ${selector.name}`);\n };\n }\n }\n\n throw new Error(`Unknown selector type: ${selector.type}`);\n}\n\n/**\n * @callback TraverseOptionFallback\n * @param {external:AST} node The given node.\n * @returns {string[]} An array of visitor keys for the given node.\n */\n\n/**\n * @callback ClassMatcher\n * @param {string} className The name of the class to match.\n * @param {external:AST} node The node to match against.\n * @param {Array} ancestry The ancestry of the node.\n * @returns {boolean} True if the node matches the class, false if not.\n */\n\n/**\n * @typedef {object} ESQueryOptions\n * @property {string} [nodeTypeKey=\"type\"] By passing `nodeTypeKey`, we can allow other ASTs to use ESQuery.\n * @property { { [nodeType: string]: string[] } } [visitorKeys] By passing `visitorKeys` mapping, we can extend the properties of the nodes that traverse the node.\n * @property {TraverseOptionFallback} [fallback] By passing `fallback` option, we can control the properties of traversing nodes when encountering unknown nodes.\n * @property {ClassMatcher} [matchClass] By passing `matchClass` option, we can customize the interpretation of classes.\n */\n\n/**\n * Given a `node` and its ancestors, determine if `node` is matched\n * by `selector`.\n * @param {?external:AST} node\n * @param {?SelectorAST} selector\n * @param {external:AST[]} [ancestry=[]]\n * @param {ESQueryOptions} [options]\n * @throws {Error} Unknowns (operator, class name, selector type, or\n * selector value type)\n * @returns {boolean}\n */\nfunction matches(node, selector, ancestry, options) {\n if (!selector) { return true; }\n if (!node) { return false; }\n if (!ancestry) { ancestry = []; }\n\n return getMatcher(selector)(node, ancestry, options);\n}\n\n/**\n * Get visitor keys of a given node.\n * @param {external:AST} node The AST node to get keys.\n * @param {ESQueryOptions|undefined} options\n * @returns {string[]} Visitor keys of the node.\n */\nfunction getVisitorKeys(node, options) {\n const nodeTypeKey = (options && options.nodeTypeKey) || 'type';\n\n const nodeType = node[nodeTypeKey];\n if (options && options.visitorKeys && options.visitorKeys[nodeType]) {\n return options.visitorKeys[nodeType];\n }\n if (estraverse.VisitorKeys[nodeType]) {\n return estraverse.VisitorKeys[nodeType];\n }\n if (options && typeof options.fallback === 'function') {\n return options.fallback(node);\n }\n // 'iteration' fallback\n return Object.keys(node).filter(function (key) {\n return key !== nodeTypeKey;\n });\n}\n\n\n/**\n * Check whether the given value is an ASTNode or not.\n * @param {any} node The value to check.\n * @param {ESQueryOptions|undefined} options The options to use.\n * @returns {boolean} `true` if the value is an ASTNode.\n */\nfunction isNode(node, options) {\n const nodeTypeKey = (options && options.nodeTypeKey) || 'type';\n return node !== null && typeof node === 'object' && typeof node[nodeTypeKey] === 'string';\n}\n\n/**\n * Determines if the given node has a sibling that matches the\n * given selector matcher.\n * @param {external:AST} node\n * @param {SelectorMatcher} matcher\n * @param {external:AST[]} ancestry\n * @param {Side} side\n * @param {ESQueryOptions|undefined} options\n * @returns {boolean}\n */\nfunction sibling(node, matcher, ancestry, side, options) {\n const [parent] = ancestry;\n if (!parent) { return false; }\n const keys = getVisitorKeys(parent, options);\n for (let i = 0; i < keys.length; ++i) {\n const listProp = parent[keys[i]];\n if (Array.isArray(listProp)) {\n const startIndex = listProp.indexOf(node);\n if (startIndex < 0) { continue; }\n let lowerBound, upperBound;\n if (side === LEFT_SIDE) {\n lowerBound = 0;\n upperBound = startIndex;\n } else {\n lowerBound = startIndex + 1;\n upperBound = listProp.length;\n }\n for (let k = lowerBound; k < upperBound; ++k) {\n if (isNode(listProp[k], options) && matcher(listProp[k], ancestry, options)) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\n/**\n * Determines if the given node has an adjacent sibling that matches\n * the given selector matcher.\n * @param {external:AST} node\n * @param {SelectorMatcher} matcher\n * @param {external:AST[]} ancestry\n * @param {Side} side\n * @param {ESQueryOptions|undefined} options\n * @returns {boolean}\n */\nfunction adjacent(node, matcher, ancestry, side, options) {\n const [parent] = ancestry;\n if (!parent) { return false; }\n const keys = getVisitorKeys(parent, options);\n for (let i = 0; i < keys.length; ++i) {\n const listProp = parent[keys[i]];\n if (Array.isArray(listProp)) {\n const idx = listProp.indexOf(node);\n if (idx < 0) { continue; }\n if (side === LEFT_SIDE && idx > 0 && isNode(listProp[idx - 1], options) && matcher(listProp[idx - 1], ancestry, options)) {\n return true;\n }\n if (side === RIGHT_SIDE && idx < listProp.length - 1 && isNode(listProp[idx + 1], options) && matcher(listProp[idx + 1], ancestry, options)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Determines if the given node is the `nth` child.\n * If `nth` is negative then the position is counted\n * from the end of the list of children.\n * @param {external:AST} node\n * @param {external:AST[]} ancestry\n * @param {Integer} nth\n * @param {ESQueryOptions|undefined} options\n * @returns {boolean}\n */\nfunction nthChild(node, ancestry, nth, options) {\n if (nth === 0) { return false; }\n const [parent] = ancestry;\n if (!parent) { return false; }\n const keys = getVisitorKeys(parent, options);\n for (let i = 0; i < keys.length; ++i) {\n const listProp = parent[keys[i]];\n if (Array.isArray(listProp)){\n const idx = nth < 0 ? listProp.length + nth : nth - 1;\n if (idx >= 0 && idx < listProp.length && listProp[idx] === node) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * For each selector node marked as a subject, find the portion of the\n * selector that the subject must match.\n * @param {SelectorAST} selector\n * @param {SelectorAST} [ancestor] Defaults to `selector`\n * @returns {SelectorAST[]}\n */\nfunction subjects(selector, ancestor) {\n if (selector == null || typeof selector != 'object') { return []; }\n if (ancestor == null) { ancestor = selector; }\n const results = selector.subject ? [ancestor] : [];\n const keys = Object.keys(selector);\n for (let i = 0; i < keys.length; ++i) {\n const p = keys[i];\n const sel = selector[p];\n results.push(...subjects(sel, p === 'left' ? sel : ancestor));\n }\n return results;\n}\n\n/**\n* @callback TraverseVisitor\n* @param {?external:AST} node\n* @param {?external:AST} parent\n* @param {external:AST[]} ancestry\n*/\n\n/**\n * From a JS AST and a selector AST, collect all JS AST nodes that\n * match the selector.\n * @param {external:AST} ast\n * @param {?SelectorAST} selector\n * @param {TraverseVisitor} visitor\n * @param {ESQueryOptions} [options]\n * @returns {external:AST[]}\n */\nfunction traverse(ast, selector, visitor, options) {\n if (!selector) { return; }\n const ancestry = [];\n const matcher = getMatcher(selector);\n const altSubjects = subjects(selector).map(getMatcher);\n estraverse.traverse(ast, {\n enter (node, parent) {\n if (parent != null) { ancestry.unshift(parent); }\n if (matcher(node, ancestry, options)) {\n if (altSubjects.length) {\n for (let i = 0, l = altSubjects.length; i < l; ++i) {\n if (altSubjects[i](node, ancestry, options)) {\n visitor(node, parent, ancestry);\n }\n for (let k = 0, m = ancestry.length; k < m; ++k) {\n const succeedingAncestry = ancestry.slice(k + 1);\n if (altSubjects[i](ancestry[k], succeedingAncestry, options)) {\n visitor(ancestry[k], parent, succeedingAncestry);\n }\n }\n }\n } else {\n visitor(node, parent, ancestry);\n }\n }\n },\n leave () { ancestry.shift(); },\n keys: options && options.visitorKeys,\n fallback: options && options.fallback || 'iteration'\n });\n}\n\n\n/**\n * From a JS AST and a selector AST, collect all JS AST nodes that\n * match the selector.\n * @param {external:AST} ast\n * @param {?SelectorAST} selector\n * @param {ESQueryOptions} [options]\n * @returns {external:AST[]}\n */\nfunction match(ast, selector, options) {\n const results = [];\n traverse(ast, selector, function (node) {\n results.push(node);\n }, options);\n return results;\n}\n\n/**\n * Parse a selector string and return its AST.\n * @param {string} selector\n * @returns {SelectorAST}\n */\nfunction parse(selector) {\n return parser.parse(selector);\n}\n\n/**\n * Query the code AST using the selector string.\n * @param {external:AST} ast\n * @param {string} selector\n * @param {ESQueryOptions} [options]\n * @returns {external:AST[]}\n */\nfunction query(ast, selector, options) {\n return match(ast, parse(selector), options);\n}\n\nquery.parse = parse;\nquery.match = match;\nquery.traverse = traverse;\nquery.matches = matches;\nquery.query = query;\n\nexport default query;\n"],"names":["module","exports","peg$SyntaxError","message","expected","found","location","this","name","Error","captureStackTrace","child","parent","ctor","constructor","prototype","peg$subclass","buildMessage","DESCRIBE_EXPECTATION_FNS","literal","expectation","literalEscape","text","class","i","escapedParts","parts","length","Array","classEscape","inverted","any","end","other","description","hex","ch","charCodeAt","toString","toUpperCase","s","replace","j","descriptions","type","sort","slice","join","describeExpected","describeFound","SyntaxError","parse","input","options","peg$result","peg$FAILED","peg$startRuleFunctions","start","peg$parsestart","peg$startRuleFunction","peg$c3","peg$literalExpectation","peg$c4","peg$c5","peg$classExpectation","peg$c8","peg$c11","peg$c14","peg$c18","peg$c19","ss","concat","map","peg$c23","peg$c26","peg$c29","peg$c32","peg$c34","peg$c36","peg$c37","peg$c39","peg$c40","a","peg$c41","peg$c42","peg$c44","peg$c46","op","value","operator","peg$c49","peg$c50","peg$c51","peg$c53","peg$c54","peg$c55","b","peg$c56","d","match","peg$c58","peg$c59","peg$c60","peg$c61","peg$c62","peg$c66","peg$c67","peg$c68","peg$c70","peg$c72","peg$c73","peg$c75","peg$c77","peg$c78","peg$c81","peg$c82","peg$c86","peg$c89","peg$c90","selectors","peg$c92","peg$c94","peg$c97","peg$c100","peg$c103","peg$c106","peg$c109","peg$currPos","peg$posDetailsCache","line","column","peg$maxFailPos","peg$maxFailExpected","peg$resultsCache","startRule","ignoreCase","peg$computePosDetails","pos","p","details","peg$computeLocation","startPos","endPos","startPosDetails","endPosDetails","offset","peg$fail","push","s0","s1","s2","key","cached","nextPos","result","peg$parse_","peg$parseselectors","peg$c1","peg$parseidentifierName","test","charAt","peg$parsebinaryOp","s3","s4","s5","s6","s7","peg$parseselector","peg$parsehasSelector","left","right","peg$parsesequence","reduce","memo","rhs","subject","as","peg$parseatom","peg$parsewildcard","peg$parseidentifier","peg$parseattrName","peg$parseattrEqOps","substr","peg$parsetype","flgs","peg$parsere_character_class","peg$parsere_escape","peg$parsere_chars","peg$parseflags","RegExp","peg$parseregex","peg$parseattrOps","peg$parsestring","leadingDecimals","apply","parseFloat","peg$parsenumber","peg$parsepath","peg$parseattrValue","peg$parseattr","peg$parsefield","peg$parsenegation","peg$parsematches","peg$parseis","peg$parsehasSelectors","peg$parsehas","nth","peg$parsefirstChild","nthLast","peg$parselastChild","parseInt","peg$parsenthChild","peg$parsenthLastChild","peg$parseclass","n","index","factory","getPath","obj","keys","MATCHER_CACHE","WeakMap","getMatcher","selector","matcher","get","generateMatcher","set","toLowerCase","node","ancestry","nodeTypeKey","path","split","inPath","ancestor","fromPathIndex","current","field","isArray","k","matchers","estraverse","traverse","enter","unshift","leave","shift","visitorKeys","fallback","l","_typeof","sibling","adjacent","nthChild","matchClass","getVisitorKeys","nodeType","VisitorKeys","Object","filter","isNode","side","_slicedToArray","listProp","startIndex","indexOf","lowerBound","upperBound","idx","ast","visitor","altSubjects","subjects","results","sel","_toConsumableArray","m","succeedingAncestry","parser","query","matches"],"mappings":"imEAQ2CA,EAAOC,UAC9CD,UAEK,WASP,SAASE,EAAgBC,EAASC,EAAUC,EAAOC,GACjDC,KAAKJ,QAAWA,EAChBI,KAAKH,SAAWA,EAChBG,KAAKF,MAAWA,EAChBE,KAAKD,SAAWA,EAChBC,KAAKC,KAAW,cAEuB,mBAA5BC,MAAMC,mBACfD,MAAMC,kBAAkBH,KAAML,GA41FlC,OA12FA,SAAsBS,EAAOC,GAC3B,SAASC,IAASN,KAAKO,YAAcH,EACrCE,EAAKE,UAA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/dist/esquery.min.js new file mode 100644 index 0000000000000000000000000000000000000000..a972bf741206d614c37e6dccad0e0812f50542f8 --- /dev/null +++ b/node_modules/esquery/dist/esquery.min.js @@ -0,0 +1,2 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).esquery=t()}(this,(function(){"use strict";function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r=0;--r)if(e[r].node===t)return!0;return!1}function y(e,t){return(new f).traverse(e,t)}function m(e,t){var r;return r=function(e,t){var r,n,o,a;for(n=e.length,o=0;n;)t(e[a=o+(r=n>>>1)])?n=r:(o=a+1,n-=r+1);return o}(t,(function(t){return t.range[0]>e.range[0]})),e.extendedRange=[e.range[0],e.range[1]],r!==t.length&&(e.extendedRange[1]=t[r].range[0]),(r-=1)>=0&&(e.extendedRange[0]=t[r].range[1]),e}return r={AssignmentExpression:"AssignmentExpression",AssignmentPattern:"AssignmentPattern",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ChainExpression:"ChainExpression",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportAllDeclaration:"ExportAllDeclaration",ExportDefaultDeclaration:"ExportDefaultDeclaration",ExportNamedDeclaration:"ExportNamedDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportExpression:"ImportExpression",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MetaProperty:"MetaProperty",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",PrivateIdentifier:"PrivateIdentifier",Program:"Program",Property:"Property",PropertyDefinition:"PropertyDefinition",RestElement:"RestElement",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",Super:"Super",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"},o={AssignmentExpression:["left","right"],AssignmentPattern:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","body"],AwaitExpression:["argument"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ChainExpression:["expression"],ClassBody:["body"],ClassDeclaration:["id","superClass","body"],ClassExpression:["id","superClass","body"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportAllDeclaration:["source"],ExportDefaultDeclaration:["declaration"],ExportNamedDeclaration:["declaration","specifiers","source"],ExportSpecifier:["exported","local"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","body"],FunctionExpression:["id","params","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportExpression:["source"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["local"],ImportNamespaceSpecifier:["local"],ImportSpecifier:["imported","local"],Literal:[],LabeledStatement:["label","body"],LogicalExpression:["left","right"],MemberExpression:["object","property"],MetaProperty:["meta","property"],MethodDefinition:["key","value"],ModuleSpecifier:[],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],PrivateIdentifier:[],Program:["body"],Property:["key","value"],PropertyDefinition:["key","value"],RestElement:["argument"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],Super:[],SwitchStatement:["discriminant","cases"],SwitchCase:["test","consequent"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handler","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"]},n={Break:a={},Skip:i={},Remove:s={}},l.prototype.replace=function(e){this.parent[this.key]=e},l.prototype.remove=function(){return Array.isArray(this.parent)?(this.parent.splice(this.key,1),!0):(this.replace(null),!1)},f.prototype.path=function(){var e,t,r,n,o;function a(e,t){if(Array.isArray(t))for(r=0,n=t.length;r=0;)if(v=s[f=x[y]])if(Array.isArray(v)){for(m=v.length;(m-=1)>=0;)if(v[m]&&!d(n,v[m])){if(h(u,x[y]))o=new c(v[m],[f,m],"Property",null);else{if(!p(v[m]))continue;o=new c(v[m],[f,m],null,null)}r.push(o)}}else if(p(v)){if(d(n,v))continue;r.push(new c(v,f,null,null))}}}else if(o=n.pop(),l=this.__execute(t.leave,o),this.__state===a||l===a)return},f.prototype.replace=function(e,t){var r,n,o,u,f,d,y,m,x,v,g,A,E;function b(e){var t,n,o,a;if(e.ref.remove())for(n=e.ref.key,a=e.ref.parent,t=r.length;t--;)if((o=r[t]).ref&&o.ref.parent===a){if(o.ref.key=0;)if(v=o[E=x[y]])if(Array.isArray(v)){for(m=v.length;(m-=1)>=0;)if(v[m]){if(h(u,x[y]))d=new c(v[m],[E,m],"Property",new l(v,m));else{if(!p(v[m]))continue;d=new c(v[m],[E,m],null,new l(v,m))}r.push(d)}}else p(v)&&r.push(new c(v,E,null,new l(o,E)))}}else if(d=n.pop(),void 0!==(f=this.__execute(t.leave,d))&&f!==a&&f!==i&&f!==s&&d.ref.replace(f),this.__state!==s&&f!==s||b(d),this.__state===a||f===a)return A.root;return A.root},t.Syntax=r,t.traverse=y,t.replace=function(e,t){return(new f).replace(e,t)},t.attachComments=function(e,t,r){var o,a,i,s,l=[];if(!e.range)throw new Error("attachComments needs range information");if(!r.length){if(t.length){for(i=0,a=t.length;ie.range[0]);)t.extendedRange[1]===e.range[0]?(e.leadingComments||(e.leadingComments=[]),e.leadingComments.push(t),l.splice(s,1)):s+=1;return s===l.length?n.Break:l[s].extendedRange[0]>e.range[1]?n.Skip:void 0}}),s=0,y(e,{leave:function(e){for(var t;se.range[1]?n.Skip:void 0}}),e},t.VisitorKeys=o,t.VisitorOption=n,t.Controller=f,t.cloneEnvironment=function(){return e({})},t}(t)})),s=a((function(e){e.exports&&(e.exports=function(){function e(t,r,n,o){this.message=t,this.expected=r,this.found=n,this.location=o,this.name="SyntaxError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,e)}return function(e,t){function r(){this.constructor=e}r.prototype=t.prototype,e.prototype=new r}(e,Error),e.buildMessage=function(e,t){var r={literal:function(e){return'"'+o(e.text)+'"'},class:function(e){var t,r="";for(t=0;t0){for(t=1,n=1;t<~+.]/,p=me([" ","[","]",",","(",")",":","#","!","=",">","<","~","+","."],!0,!1),h=ye(">",!1),d=ye("~",!1),y=ye("+",!1),m=ye(",",!1),x=function(e,t){return[e].concat(t.map((function(e){return e[3]})))},v=ye("!",!1),g=ye("*",!1),A=ye("#",!1),E=ye("[",!1),b=ye("]",!1),S=/^[>","<","!"],!1,!1),C=ye("=",!1),P=function(e){return(e||"")+"="},w=/^[><]/,k=me([">","<"],!1,!1),D=ye(".",!1),I=function(e,t,r){return{type:"attribute",name:e,operator:t,value:r}},j=ye('"',!1),T=/^[^\\"]/,F=me(["\\",'"'],!0,!1),R=ye("\\",!1),O={type:"any"},L=function(e,t){return e+t},M=function(e){return{type:"literal",value:(t=e.join(""),t.replace(/\\(.)/g,(function(e,t){switch(t){case"b":return"\b";case"f":return"\f";case"n":return"\n";case"r":return"\r";case"t":return"\t";case"v":return"\v";default:return t}})))};var t},B=ye("'",!1),U=/^[^\\']/,K=me(["\\","'"],!0,!1),N=/^[0-9]/,W=me([["0","9"]],!1,!1),q=ye("type(",!1),V=/^[^ )]/,G=me([" ",")"],!0,!1),z=ye(")",!1),H=/^[imsu]/,Y=me(["i","m","s","u"],!1,!1),$=ye("/",!1),J=/^[^\]\\]/,Q=me(["]","\\"],!0,!1),X=/^[^\/\\[]/,Z=me(["/","\\","["],!0,!1),ee=ye(":not(",!1),te=ye(":matches(",!1),re=function(e){return{type:"matches",selectors:e}},ne=ye(":is(",!1),oe=ye(":has(",!1),ae=ye(":first-child",!1),ie=ye(":last-child",!1),se=ye(":nth-child(",!1),ue=ye(":nth-last-child(",!1),le=ye(":",!1),ce=0,fe=[{line:1,column:1}],pe=0,he=[],de={};if("startRule"in r){if(!(r.startRule in u))throw new Error("Can't start parsing from rule \""+r.startRule+'".');l=u[r.startRule]}function ye(e,t){return{type:"literal",text:e,ignoreCase:t}}function me(e,t,r){return{type:"class",parts:e,inverted:t,ignoreCase:r}}function xe(e){var r,n=fe[e];if(n)return n;for(r=e-1;!fe[r];)r--;for(n={line:(n=fe[r]).line,column:n.column};rpe&&(pe=ce,he=[]),he.push(e))}function Ae(){var e,t,r,n,o=36*ce+0,a=de[o];return a?(ce=a.nextPos,a.result):(e=ce,(t=Ee())!==s&&(r=_e())!==s&&Ee()!==s?e=t=1===(n=r).length?n[0]:{type:"matches",selectors:n}:(ce=e,e=s),e===s&&(e=ce,(t=Ee())!==s&&(t=void 0),e=t),de[o]={nextPos:ce,result:e},e)}function Ee(){var e,r,n=36*ce+1,o=de[n];if(o)return ce=o.nextPos,o.result;for(e=[],32===t.charCodeAt(ce)?(r=" ",ce++):(r=s,ge(c));r!==s;)e.push(r),32===t.charCodeAt(ce)?(r=" ",ce++):(r=s,ge(c));return de[n]={nextPos:ce,result:e},e}function be(){var e,r,n,o=36*ce+2,a=de[o];if(a)return ce=a.nextPos,a.result;if(r=[],f.test(t.charAt(ce))?(n=t.charAt(ce),ce++):(n=s,ge(p)),n!==s)for(;n!==s;)r.push(n),f.test(t.charAt(ce))?(n=t.charAt(ce),ce++):(n=s,ge(p));else r=s;return r!==s&&(r=r.join("")),e=r,de[o]={nextPos:ce,result:e},e}function Se(){var e,r,n,o=36*ce+3,a=de[o];return a?(ce=a.nextPos,a.result):(e=ce,(r=Ee())!==s?(62===t.charCodeAt(ce)?(n=">",ce++):(n=s,ge(h)),n!==s&&Ee()!==s?e=r="child":(ce=e,e=s)):(ce=e,e=s),e===s&&(e=ce,(r=Ee())!==s?(126===t.charCodeAt(ce)?(n="~",ce++):(n=s,ge(d)),n!==s&&Ee()!==s?e=r="sibling":(ce=e,e=s)):(ce=e,e=s),e===s&&(e=ce,(r=Ee())!==s?(43===t.charCodeAt(ce)?(n="+",ce++):(n=s,ge(y)),n!==s&&Ee()!==s?e=r="adjacent":(ce=e,e=s)):(ce=e,e=s),e===s&&(e=ce,32===t.charCodeAt(ce)?(r=" ",ce++):(r=s,ge(c)),r!==s&&(n=Ee())!==s?e=r="descendant":(ce=e,e=s)))),de[o]={nextPos:ce,result:e},e)}function _e(){var e,r,n,o,a,i,u,l,c=36*ce+5,f=de[c];if(f)return ce=f.nextPos,f.result;if(e=ce,(r=Pe())!==s){for(n=[],o=ce,(a=Ee())!==s?(44===t.charCodeAt(ce)?(i=",",ce++):(i=s,ge(m)),i!==s&&(u=Ee())!==s&&(l=Pe())!==s?o=a=[a,i,u,l]:(ce=o,o=s)):(ce=o,o=s);o!==s;)n.push(o),o=ce,(a=Ee())!==s?(44===t.charCodeAt(ce)?(i=",",ce++):(i=s,ge(m)),i!==s&&(u=Ee())!==s&&(l=Pe())!==s?o=a=[a,i,u,l]:(ce=o,o=s)):(ce=o,o=s);n!==s?e=r=x(r,n):(ce=e,e=s)}else ce=e,e=s;return de[c]={nextPos:ce,result:e},e}function Ce(){var e,t,r,n,o,a=36*ce+6,i=de[a];return i?(ce=i.nextPos,i.result):(e=ce,(t=Se())===s&&(t=null),t!==s&&(r=Pe())!==s?(o=r,e=t=(n=t)?{type:n,left:{type:"exactNode"},right:o}:o):(ce=e,e=s),de[a]={nextPos:ce,result:e},e)}function Pe(){var e,t,r,n,o,a,i,u=36*ce+7,l=de[u];if(l)return ce=l.nextPos,l.result;if(e=ce,(t=we())!==s){for(r=[],n=ce,(o=Se())!==s&&(a=we())!==s?n=o=[o,a]:(ce=n,n=s);n!==s;)r.push(n),n=ce,(o=Se())!==s&&(a=we())!==s?n=o=[o,a]:(ce=n,n=s);r!==s?(i=t,e=t=r.reduce((function(e,t){return{type:t[0],left:e,right:t[1]}}),i)):(ce=e,e=s)}else ce=e,e=s;return de[u]={nextPos:ce,result:e},e}function we(){var e,r,n,o,a,i,u,l=36*ce+8,c=de[l];if(c)return ce=c.nextPos,c.result;if(e=ce,33===t.charCodeAt(ce)?(r="!",ce++):(r=s,ge(v)),r===s&&(r=null),r!==s){if(n=[],(o=ke())!==s)for(;o!==s;)n.push(o),o=ke();else n=s;n!==s?(a=r,u=1===(i=n).length?i[0]:{type:"compound",selectors:i},a&&(u.subject=!0),e=r=u):(ce=e,e=s)}else ce=e,e=s;return de[l]={nextPos:ce,result:e},e}function ke(){var e,r=36*ce+9,n=de[r];return n?(ce=n.nextPos,n.result):((e=function(){var e,r,n=36*ce+10,o=de[n];return o?(ce=o.nextPos,o.result):(42===t.charCodeAt(ce)?(r="*",ce++):(r=s,ge(g)),r!==s&&(r={type:"wildcard",value:r}),e=r,de[n]={nextPos:ce,result:e},e)}())===s&&(e=function(){var e,r,n,o=36*ce+11,a=de[o];return a?(ce=a.nextPos,a.result):(e=ce,35===t.charCodeAt(ce)?(r="#",ce++):(r=s,ge(A)),r===s&&(r=null),r!==s&&(n=be())!==s?e=r={type:"identifier",value:n}:(ce=e,e=s),de[o]={nextPos:ce,result:e},e)}())===s&&(e=function(){var e,r,n,o,a=36*ce+12,i=de[a];return i?(ce=i.nextPos,i.result):(e=ce,91===t.charCodeAt(ce)?(r="[",ce++):(r=s,ge(E)),r!==s&&Ee()!==s&&(n=function(){var e,r,n,o,a=36*ce+16,i=de[a];return i?(ce=i.nextPos,i.result):(e=ce,(r=De())!==s&&Ee()!==s&&(n=function(){var e,r,n,o=36*ce+14,a=de[o];return a?(ce=a.nextPos,a.result):(e=ce,33===t.charCodeAt(ce)?(r="!",ce++):(r=s,ge(v)),r===s&&(r=null),r!==s?(61===t.charCodeAt(ce)?(n="=",ce++):(n=s,ge(C)),n!==s?(r=P(r),e=r):(ce=e,e=s)):(ce=e,e=s),de[o]={nextPos:ce,result:e},e)}())!==s&&Ee()!==s?((o=function(){var e,r,n,o,a,i=36*ce+20,u=de[i];if(u)return ce=u.nextPos,u.result;if(e=ce,"type("===t.substr(ce,5)?(r="type(",ce+=5):(r=s,ge(q)),r!==s)if(Ee()!==s){if(n=[],V.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(G)),o!==s)for(;o!==s;)n.push(o),V.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(G));else n=s;n!==s&&(o=Ee())!==s?(41===t.charCodeAt(ce)?(a=")",ce++):(a=s,ge(z)),a!==s?(r={type:"type",value:n.join("")},e=r):(ce=e,e=s)):(ce=e,e=s)}else ce=e,e=s;else ce=e,e=s;return de[i]={nextPos:ce,result:e},e}())===s&&(o=function(){var e,r,n,o,a,i,u=36*ce+22,l=de[u];if(l)return ce=l.nextPos,l.result;if(e=ce,47===t.charCodeAt(ce)?(r="/",ce++):(r=s,ge($)),r!==s){if(n=[],(o=Ie())===s&&(o=je())===s&&(o=Te()),o!==s)for(;o!==s;)n.push(o),(o=Ie())===s&&(o=je())===s&&(o=Te());else n=s;n!==s?(47===t.charCodeAt(ce)?(o="/",ce++):(o=s,ge($)),o!==s?((a=function(){var e,r,n=36*ce+21,o=de[n];if(o)return ce=o.nextPos,o.result;if(e=[],H.test(t.charAt(ce))?(r=t.charAt(ce),ce++):(r=s,ge(Y)),r!==s)for(;r!==s;)e.push(r),H.test(t.charAt(ce))?(r=t.charAt(ce),ce++):(r=s,ge(Y));else e=s;return de[n]={nextPos:ce,result:e},e}())===s&&(a=null),a!==s?(i=a,r={type:"regexp",value:new RegExp(n.join(""),i?i.join(""):"")},e=r):(ce=e,e=s)):(ce=e,e=s)):(ce=e,e=s)}else ce=e,e=s;return de[u]={nextPos:ce,result:e},e}()),o!==s?(r=I(r,n,o),e=r):(ce=e,e=s)):(ce=e,e=s),e===s&&(e=ce,(r=De())!==s&&Ee()!==s&&(n=function(){var e,r,n,o=36*ce+13,a=de[o];return a?(ce=a.nextPos,a.result):(e=ce,S.test(t.charAt(ce))?(r=t.charAt(ce),ce++):(r=s,ge(_)),r===s&&(r=null),r!==s?(61===t.charCodeAt(ce)?(n="=",ce++):(n=s,ge(C)),n!==s?(r=P(r),e=r):(ce=e,e=s)):(ce=e,e=s),e===s&&(w.test(t.charAt(ce))?(e=t.charAt(ce),ce++):(e=s,ge(k))),de[o]={nextPos:ce,result:e},e)}())!==s&&Ee()!==s?((o=function(){var e,r,n,o,a,i,u=36*ce+17,l=de[u];if(l)return ce=l.nextPos,l.result;if(e=ce,34===t.charCodeAt(ce)?(r='"',ce++):(r=s,ge(j)),r!==s){for(n=[],T.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(F)),o===s&&(o=ce,92===t.charCodeAt(ce)?(a="\\",ce++):(a=s,ge(R)),a!==s?(t.length>ce?(i=t.charAt(ce),ce++):(i=s,ge(O)),i!==s?(a=L(a,i),o=a):(ce=o,o=s)):(ce=o,o=s));o!==s;)n.push(o),T.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(F)),o===s&&(o=ce,92===t.charCodeAt(ce)?(a="\\",ce++):(a=s,ge(R)),a!==s?(t.length>ce?(i=t.charAt(ce),ce++):(i=s,ge(O)),i!==s?(a=L(a,i),o=a):(ce=o,o=s)):(ce=o,o=s));n!==s?(34===t.charCodeAt(ce)?(o='"',ce++):(o=s,ge(j)),o!==s?(r=M(n),e=r):(ce=e,e=s)):(ce=e,e=s)}else ce=e,e=s;if(e===s)if(e=ce,39===t.charCodeAt(ce)?(r="'",ce++):(r=s,ge(B)),r!==s){for(n=[],U.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(K)),o===s&&(o=ce,92===t.charCodeAt(ce)?(a="\\",ce++):(a=s,ge(R)),a!==s?(t.length>ce?(i=t.charAt(ce),ce++):(i=s,ge(O)),i!==s?(a=L(a,i),o=a):(ce=o,o=s)):(ce=o,o=s));o!==s;)n.push(o),U.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(K)),o===s&&(o=ce,92===t.charCodeAt(ce)?(a="\\",ce++):(a=s,ge(R)),a!==s?(t.length>ce?(i=t.charAt(ce),ce++):(i=s,ge(O)),i!==s?(a=L(a,i),o=a):(ce=o,o=s)):(ce=o,o=s));n!==s?(39===t.charCodeAt(ce)?(o="'",ce++):(o=s,ge(B)),o!==s?(r=M(n),e=r):(ce=e,e=s)):(ce=e,e=s)}else ce=e,e=s;return de[u]={nextPos:ce,result:e},e}())===s&&(o=function(){var e,r,n,o,a,i,u,l=36*ce+18,c=de[l];if(c)return ce=c.nextPos,c.result;for(e=ce,r=ce,n=[],N.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(W));o!==s;)n.push(o),N.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(W));if(n!==s?(46===t.charCodeAt(ce)?(o=".",ce++):(o=s,ge(D)),o!==s?r=n=[n,o]:(ce=r,r=s)):(ce=r,r=s),r===s&&(r=null),r!==s){if(n=[],N.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(W)),o!==s)for(;o!==s;)n.push(o),N.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(W));else n=s;n!==s?(i=n,u=(a=r)?[].concat.apply([],a).join(""):"",r={type:"literal",value:parseFloat(u+i.join(""))},e=r):(ce=e,e=s)}else ce=e,e=s;return de[l]={nextPos:ce,result:e},e}())===s&&(o=function(){var e,t,r=36*ce+19,n=de[r];return n?(ce=n.nextPos,n.result):((t=be())!==s&&(t={type:"literal",value:t}),e=t,de[r]={nextPos:ce,result:e},e)}()),o!==s?(r=I(r,n,o),e=r):(ce=e,e=s)):(ce=e,e=s),e===s&&(e=ce,(r=De())!==s&&(r={type:"attribute",name:r}),e=r)),de[a]={nextPos:ce,result:e},e)}())!==s&&Ee()!==s?(93===t.charCodeAt(ce)?(o="]",ce++):(o=s,ge(b)),o!==s?e=r=n:(ce=e,e=s)):(ce=e,e=s),de[a]={nextPos:ce,result:e},e)}())===s&&(e=function(){var e,r,n,o,a,i,u,l,c=36*ce+26,f=de[c];if(f)return ce=f.nextPos,f.result;if(e=ce,46===t.charCodeAt(ce)?(r=".",ce++):(r=s,ge(D)),r!==s)if((n=be())!==s){for(o=[],a=ce,46===t.charCodeAt(ce)?(i=".",ce++):(i=s,ge(D)),i!==s&&(u=be())!==s?a=i=[i,u]:(ce=a,a=s);a!==s;)o.push(a),a=ce,46===t.charCodeAt(ce)?(i=".",ce++):(i=s,ge(D)),i!==s&&(u=be())!==s?a=i=[i,u]:(ce=a,a=s);o!==s?(l=n,r={type:"field",name:o.reduce((function(e,t){return e+t[0]+t[1]}),l)},e=r):(ce=e,e=s)}else ce=e,e=s;else ce=e,e=s;return de[c]={nextPos:ce,result:e},e}())===s&&(e=function(){var e,r,n,o,a=36*ce+27,i=de[a];return i?(ce=i.nextPos,i.result):(e=ce,":not("===t.substr(ce,5)?(r=":not(",ce+=5):(r=s,ge(ee)),r!==s&&Ee()!==s&&(n=_e())!==s&&Ee()!==s?(41===t.charCodeAt(ce)?(o=")",ce++):(o=s,ge(z)),o!==s?e=r={type:"not",selectors:n}:(ce=e,e=s)):(ce=e,e=s),de[a]={nextPos:ce,result:e},e)}())===s&&(e=function(){var e,r,n,o,a=36*ce+28,i=de[a];return i?(ce=i.nextPos,i.result):(e=ce,":matches("===t.substr(ce,9)?(r=":matches(",ce+=9):(r=s,ge(te)),r!==s&&Ee()!==s&&(n=_e())!==s&&Ee()!==s?(41===t.charCodeAt(ce)?(o=")",ce++):(o=s,ge(z)),o!==s?(r=re(n),e=r):(ce=e,e=s)):(ce=e,e=s),de[a]={nextPos:ce,result:e},e)}())===s&&(e=function(){var e,r,n,o,a=36*ce+29,i=de[a];return i?(ce=i.nextPos,i.result):(e=ce,":is("===t.substr(ce,4)?(r=":is(",ce+=4):(r=s,ge(ne)),r!==s&&Ee()!==s&&(n=_e())!==s&&Ee()!==s?(41===t.charCodeAt(ce)?(o=")",ce++):(o=s,ge(z)),o!==s?(r=re(n),e=r):(ce=e,e=s)):(ce=e,e=s),de[a]={nextPos:ce,result:e},e)}())===s&&(e=function(){var e,r,n,o,a=36*ce+30,i=de[a];return i?(ce=i.nextPos,i.result):(e=ce,":has("===t.substr(ce,5)?(r=":has(",ce+=5):(r=s,ge(oe)),r!==s&&Ee()!==s&&(n=function(){var e,r,n,o,a,i,u,l,c=36*ce+4,f=de[c];if(f)return ce=f.nextPos,f.result;if(e=ce,(r=Ce())!==s){for(n=[],o=ce,(a=Ee())!==s?(44===t.charCodeAt(ce)?(i=",",ce++):(i=s,ge(m)),i!==s&&(u=Ee())!==s&&(l=Ce())!==s?o=a=[a,i,u,l]:(ce=o,o=s)):(ce=o,o=s);o!==s;)n.push(o),o=ce,(a=Ee())!==s?(44===t.charCodeAt(ce)?(i=",",ce++):(i=s,ge(m)),i!==s&&(u=Ee())!==s&&(l=Ce())!==s?o=a=[a,i,u,l]:(ce=o,o=s)):(ce=o,o=s);n!==s?e=r=x(r,n):(ce=e,e=s)}else ce=e,e=s;return de[c]={nextPos:ce,result:e},e}())!==s&&Ee()!==s?(41===t.charCodeAt(ce)?(o=")",ce++):(o=s,ge(z)),o!==s?e=r={type:"has",selectors:n}:(ce=e,e=s)):(ce=e,e=s),de[a]={nextPos:ce,result:e},e)}())===s&&(e=function(){var e,r,n=36*ce+31,o=de[n];return o?(ce=o.nextPos,o.result):(":first-child"===t.substr(ce,12)?(r=":first-child",ce+=12):(r=s,ge(ae)),r!==s&&(r=Fe(1)),e=r,de[n]={nextPos:ce,result:e},e)}())===s&&(e=function(){var e,r,n=36*ce+32,o=de[n];return o?(ce=o.nextPos,o.result):(":last-child"===t.substr(ce,11)?(r=":last-child",ce+=11):(r=s,ge(ie)),r!==s&&(r=Re(1)),e=r,de[n]={nextPos:ce,result:e},e)}())===s&&(e=function(){var e,r,n,o,a,i=36*ce+33,u=de[i];if(u)return ce=u.nextPos,u.result;if(e=ce,":nth-child("===t.substr(ce,11)?(r=":nth-child(",ce+=11):(r=s,ge(se)),r!==s)if(Ee()!==s){if(n=[],N.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(W)),o!==s)for(;o!==s;)n.push(o),N.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(W));else n=s;n!==s&&(o=Ee())!==s?(41===t.charCodeAt(ce)?(a=")",ce++):(a=s,ge(z)),a!==s?(r=Fe(parseInt(n.join(""),10)),e=r):(ce=e,e=s)):(ce=e,e=s)}else ce=e,e=s;else ce=e,e=s;return de[i]={nextPos:ce,result:e},e}())===s&&(e=function(){var e,r,n,o,a,i=36*ce+34,u=de[i];if(u)return ce=u.nextPos,u.result;if(e=ce,":nth-last-child("===t.substr(ce,16)?(r=":nth-last-child(",ce+=16):(r=s,ge(ue)),r!==s)if(Ee()!==s){if(n=[],N.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(W)),o!==s)for(;o!==s;)n.push(o),N.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(W));else n=s;n!==s&&(o=Ee())!==s?(41===t.charCodeAt(ce)?(a=")",ce++):(a=s,ge(z)),a!==s?(r=Re(parseInt(n.join(""),10)),e=r):(ce=e,e=s)):(ce=e,e=s)}else ce=e,e=s;else ce=e,e=s;return de[i]={nextPos:ce,result:e},e}())===s&&(e=function(){var e,r,n,o=36*ce+35,a=de[o];return a?(ce=a.nextPos,a.result):(e=ce,58===t.charCodeAt(ce)?(r=":",ce++):(r=s,ge(le)),r!==s&&(n=be())!==s?e=r={type:"class",name:n}:(ce=e,e=s),de[o]={nextPos:ce,result:e},e)}()),de[r]={nextPos:ce,result:e},e)}function De(){var e,r,n,o,a,i,u,l,c=36*ce+15,f=de[c];if(f)return ce=f.nextPos,f.result;if(e=ce,(r=be())!==s){for(n=[],o=ce,46===t.charCodeAt(ce)?(a=".",ce++):(a=s,ge(D)),a!==s&&(i=be())!==s?o=a=[a,i]:(ce=o,o=s);o!==s;)n.push(o),o=ce,46===t.charCodeAt(ce)?(a=".",ce++):(a=s,ge(D)),a!==s&&(i=be())!==s?o=a=[a,i]:(ce=o,o=s);n!==s?(u=r,l=n,e=r=[].concat.apply([u],l).join("")):(ce=e,e=s)}else ce=e,e=s;return de[c]={nextPos:ce,result:e},e}function Ie(){var e,r,n,o,a=36*ce+23,i=de[a];if(i)return ce=i.nextPos,i.result;if(e=ce,91===t.charCodeAt(ce)?(r="[",ce++):(r=s,ge(E)),r!==s){if(n=[],J.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(Q)),o===s&&(o=je()),o!==s)for(;o!==s;)n.push(o),J.test(t.charAt(ce))?(o=t.charAt(ce),ce++):(o=s,ge(Q)),o===s&&(o=je());else n=s;n!==s?(93===t.charCodeAt(ce)?(o="]",ce++):(o=s,ge(b)),o!==s?e=r="["+n.join("")+"]":(ce=e,e=s)):(ce=e,e=s)}else ce=e,e=s;return de[a]={nextPos:ce,result:e},e}function je(){var e,r,n,o=36*ce+24,a=de[o];return a?(ce=a.nextPos,a.result):(e=ce,92===t.charCodeAt(ce)?(r="\\",ce++):(r=s,ge(R)),r!==s?(t.length>ce?(n=t.charAt(ce),ce++):(n=s,ge(O)),n!==s?e=r="\\"+n:(ce=e,e=s)):(ce=e,e=s),de[o]={nextPos:ce,result:e},e)}function Te(){var e,r,n,o=36*ce+25,a=de[o];if(a)return ce=a.nextPos,a.result;if(r=[],X.test(t.charAt(ce))?(n=t.charAt(ce),ce++):(n=s,ge(Z)),n!==s)for(;n!==s;)r.push(n),X.test(t.charAt(ce))?(n=t.charAt(ce),ce++):(n=s,ge(Z));else r=s;return r!==s&&(r=r.join("")),e=r,de[o]={nextPos:ce,result:e},e}function Fe(e){return{type:"nth-child",index:{type:"literal",value:e}}}function Re(e){return{type:"nth-last-child",index:{type:"literal",value:e}}}if((n=l())!==s&&ce===t.length)return n;throw n!==s&&ce0&&p(e,t,r))&&f(t[0],t.slice(1),r)};case"descendant":var h=c(e.left),x=c(e.right);return function(e,t,r){if(x(e,t,r))for(var n=0,o=t.length;n":return function(t){return u(t,v)>e.value.value};case">=":return function(t){return u(t,v)>=e.value.value}}throw new Error("Unknown operator: ".concat(e.operator));case"sibling":var E=c(e.left),b=c(e.right);return function(t,r,n){return b(t,r,n)&&d(t,E,r,"LEFT_SIDE",n)||e.left.subject&&E(t,r,n)&&d(t,b,r,"RIGHT_SIDE",n)};case"adjacent":var S=c(e.left),_=c(e.right);return function(t,r,n){return _(t,r,n)&&y(t,S,r,"LEFT_SIDE",n)||e.right.subject&&S(t,r,n)&&y(t,_,r,"RIGHT_SIDE",n)};case"nth-child":var C=e.index.value,P=c(e.right);return function(e,t,r){return P(e,t,r)&&m(e,t,C,r)};case"nth-last-child":var w=-e.index.value,k=c(e.right);return function(e,t,r){return k(e,t,r)&&m(e,t,w,r)};case"class":var D=e.name.toLowerCase();return function(t,r,n){if(n&&n.matchClass)return n.matchClass(e.name,t,r);if(n&&n.nodeTypeKey)return!1;switch(D){case"statement":if("Statement"===t.type.slice(-9))return!0;case"declaration":return"Declaration"===t.type.slice(-11);case"pattern":if("Pattern"===t.type.slice(-7))return!0;case"expression":return"Expression"===t.type.slice(-10)||"Literal"===t.type.slice(-7)||"Identifier"===t.type&&(0===r.length||"MetaProperty"!==r[0].type)||"MetaProperty"===t.type;case"function":return"FunctionDeclaration"===t.type||"FunctionExpression"===t.type||"ArrowFunctionExpression"===t.type}throw new Error("Unknown class name: ".concat(e.name))}}throw new Error("Unknown selector type: ".concat(e.type))}function p(e,t){var r=t&&t.nodeTypeKey||"type",n=e[r];return t&&t.visitorKeys&&t.visitorKeys[n]?t.visitorKeys[n]:i.VisitorKeys[n]?i.VisitorKeys[n]:t&&"function"==typeof t.fallback?t.fallback(e):Object.keys(e).filter((function(e){return e!==r}))}function h(e,t){var r=t&&t.nodeTypeKey||"type";return null!==e&&"object"===n(e)&&"string"==typeof e[r]}function d(e,r,n,o,a){var i=t(n,1)[0];if(!i)return!1;for(var s=p(i,a),u=0;u0&&h(l[c-1],a)&&r(l[c-1],n,a))return!0;if("RIGHT_SIDE"===o&&c=0&&l\n Copyright (C) 2012 Ariya Hidayat \n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/*jslint vars:false, bitwise:true*/\n/*jshint indent:4*/\n/*global exports:true*/\n(function clone(exports) {\n 'use strict';\n\n var Syntax,\n VisitorOption,\n VisitorKeys,\n BREAK,\n SKIP,\n REMOVE;\n\n function deepCopy(obj) {\n var ret = {}, key, val;\n for (key in obj) {\n if (obj.hasOwnProperty(key)) {\n val = obj[key];\n if (typeof val === 'object' && val !== null) {\n ret[key] = deepCopy(val);\n } else {\n ret[key] = val;\n }\n }\n }\n return ret;\n }\n\n // based on LLVM libc++ upper_bound / lower_bound\n // MIT License\n\n function upperBound(array, func) {\n var diff, len, i, current;\n\n len = array.length;\n i = 0;\n\n while (len) {\n diff = len >>> 1;\n current = i + diff;\n if (func(array[current])) {\n len = diff;\n } else {\n i = current + 1;\n len -= diff + 1;\n }\n }\n return i;\n }\n\n Syntax = {\n AssignmentExpression: 'AssignmentExpression',\n AssignmentPattern: 'AssignmentPattern',\n ArrayExpression: 'ArrayExpression',\n ArrayPattern: 'ArrayPattern',\n ArrowFunctionExpression: 'ArrowFunctionExpression',\n AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7.\n BlockStatement: 'BlockStatement',\n BinaryExpression: 'BinaryExpression',\n BreakStatement: 'BreakStatement',\n CallExpression: 'CallExpression',\n CatchClause: 'CatchClause',\n ChainExpression: 'ChainExpression',\n ClassBody: 'ClassBody',\n ClassDeclaration: 'ClassDeclaration',\n ClassExpression: 'ClassExpression',\n ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7.\n ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7.\n ConditionalExpression: 'ConditionalExpression',\n ContinueStatement: 'ContinueStatement',\n DebuggerStatement: 'DebuggerStatement',\n DirectiveStatement: 'DirectiveStatement',\n DoWhileStatement: 'DoWhileStatement',\n EmptyStatement: 'EmptyStatement',\n ExportAllDeclaration: 'ExportAllDeclaration',\n ExportDefaultDeclaration: 'ExportDefaultDeclaration',\n ExportNamedDeclaration: 'ExportNamedDeclaration',\n ExportSpecifier: 'ExportSpecifier',\n ExpressionStatement: 'ExpressionStatement',\n ForStatement: 'ForStatement',\n ForInStatement: 'ForInStatement',\n ForOfStatement: 'ForOfStatement',\n FunctionDeclaration: 'FunctionDeclaration',\n FunctionExpression: 'FunctionExpression',\n GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7.\n Identifier: 'Identifier',\n IfStatement: 'IfStatement',\n ImportExpression: 'ImportExpression',\n ImportDeclaration: 'ImportDeclaration',\n ImportDefaultSpecifier: 'ImportDefaultSpecifier',\n ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',\n ImportSpecifier: 'ImportSpecifier',\n Literal: 'Literal',\n LabeledStatement: 'LabeledStatement',\n LogicalExpression: 'LogicalExpression',\n MemberExpression: 'MemberExpression',\n MetaProperty: 'MetaProperty',\n MethodDefinition: 'MethodDefinition',\n ModuleSpecifier: 'ModuleSpecifier',\n NewExpression: 'NewExpression',\n ObjectExpression: 'ObjectExpression',\n ObjectPattern: 'ObjectPattern',\n PrivateIdentifier: 'PrivateIdentifier',\n Program: 'Program',\n Property: 'Property',\n PropertyDefinition: 'PropertyDefinition',\n RestElement: 'RestElement',\n ReturnStatement: 'ReturnStatement',\n SequenceExpression: 'SequenceExpression',\n SpreadElement: 'SpreadElement',\n Super: 'Super',\n SwitchStatement: 'SwitchStatement',\n SwitchCase: 'SwitchCase',\n TaggedTemplateExpression: 'TaggedTemplateExpression',\n TemplateElement: 'TemplateElement',\n TemplateLiteral: 'TemplateLiteral',\n ThisExpression: 'ThisExpression',\n ThrowStatement: 'ThrowStatement',\n TryStatement: 'TryStatement',\n UnaryExpression: 'UnaryExpression',\n UpdateExpression: 'UpdateExpression',\n VariableDeclaration: 'VariableDeclaration',\n VariableDeclarator: 'VariableDeclarator',\n WhileStatement: 'WhileStatement',\n WithStatement: 'WithStatement',\n YieldExpression: 'YieldExpression'\n };\n\n VisitorKeys = {\n AssignmentExpression: ['left', 'right'],\n AssignmentPattern: ['left', 'right'],\n ArrayExpression: ['elements'],\n ArrayPattern: ['elements'],\n ArrowFunctionExpression: ['params', 'body'],\n AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7.\n BlockStatement: ['body'],\n BinaryExpression: ['left', 'right'],\n BreakStatement: ['label'],\n CallExpression: ['callee', 'arguments'],\n CatchClause: ['param', 'body'],\n ChainExpression: ['expression'],\n ClassBody: ['body'],\n ClassDeclaration: ['id', 'superClass', 'body'],\n ClassExpression: ['id', 'superClass', 'body'],\n ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7.\n ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.\n ConditionalExpression: ['test', 'consequent', 'alternate'],\n ContinueStatement: ['label'],\n DebuggerStatement: [],\n DirectiveStatement: [],\n DoWhileStatement: ['body', 'test'],\n EmptyStatement: [],\n ExportAllDeclaration: ['source'],\n ExportDefaultDeclaration: ['declaration'],\n ExportNamedDeclaration: ['declaration', 'specifiers', 'source'],\n ExportSpecifier: ['exported', 'local'],\n ExpressionStatement: ['expression'],\n ForStatement: ['init', 'test', 'update', 'body'],\n ForInStatement: ['left', 'right', 'body'],\n ForOfStatement: ['left', 'right', 'body'],\n FunctionDeclaration: ['id', 'params', 'body'],\n FunctionExpression: ['id', 'params', 'body'],\n GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.\n Identifier: [],\n IfStatement: ['test', 'consequent', 'alternate'],\n ImportExpression: ['source'],\n ImportDeclaration: ['specifiers', 'source'],\n ImportDefaultSpecifier: ['local'],\n ImportNamespaceSpecifier: ['local'],\n ImportSpecifier: ['imported', 'local'],\n Literal: [],\n LabeledStatement: ['label', 'body'],\n LogicalExpression: ['left', 'right'],\n MemberExpression: ['object', 'property'],\n MetaProperty: ['meta', 'property'],\n MethodDefinition: ['key', 'value'],\n ModuleSpecifier: [],\n NewExpression: ['callee', 'arguments'],\n ObjectExpression: ['properties'],\n ObjectPattern: ['properties'],\n PrivateIdentifier: [],\n Program: ['body'],\n Property: ['key', 'value'],\n PropertyDefinition: ['key', 'value'],\n RestElement: [ 'argument' ],\n ReturnStatement: ['argument'],\n SequenceExpression: ['expressions'],\n SpreadElement: ['argument'],\n Super: [],\n SwitchStatement: ['discriminant', 'cases'],\n SwitchCase: ['test', 'consequent'],\n TaggedTemplateExpression: ['tag', 'quasi'],\n TemplateElement: [],\n TemplateLiteral: ['quasis', 'expressions'],\n ThisExpression: [],\n ThrowStatement: ['argument'],\n TryStatement: ['block', 'handler', 'finalizer'],\n UnaryExpression: ['argument'],\n UpdateExpression: ['argument'],\n VariableDeclaration: ['declarations'],\n VariableDeclarator: ['id', 'init'],\n WhileStatement: ['test', 'body'],\n WithStatement: ['object', 'body'],\n YieldExpression: ['argument']\n };\n\n // unique id\n BREAK = {};\n SKIP = {};\n REMOVE = {};\n\n VisitorOption = {\n Break: BREAK,\n Skip: SKIP,\n Remove: REMOVE\n };\n\n function Reference(parent, key) {\n this.parent = parent;\n this.key = key;\n }\n\n Reference.prototype.replace = function replace(node) {\n this.parent[this.key] = node;\n };\n\n Reference.prototype.remove = function remove() {\n if (Array.isArray(this.parent)) {\n this.parent.splice(this.key, 1);\n return true;\n } else {\n this.replace(null);\n return false;\n }\n };\n\n function Element(node, path, wrap, ref) {\n this.node = node;\n this.path = path;\n this.wrap = wrap;\n this.ref = ref;\n }\n\n function Controller() { }\n\n // API:\n // return property path array from root to current node\n Controller.prototype.path = function path() {\n var i, iz, j, jz, result, element;\n\n function addToPath(result, path) {\n if (Array.isArray(path)) {\n for (j = 0, jz = path.length; j < jz; ++j) {\n result.push(path[j]);\n }\n } else {\n result.push(path);\n }\n }\n\n // root node\n if (!this.__current.path) {\n return null;\n }\n\n // first node is sentinel, second node is root element\n result = [];\n for (i = 2, iz = this.__leavelist.length; i < iz; ++i) {\n element = this.__leavelist[i];\n addToPath(result, element.path);\n }\n addToPath(result, this.__current.path);\n return result;\n };\n\n // API:\n // return type of current node\n Controller.prototype.type = function () {\n var node = this.current();\n return node.type || this.__current.wrap;\n };\n\n // API:\n // return array of parent elements\n Controller.prototype.parents = function parents() {\n var i, iz, result;\n\n // first node is sentinel\n result = [];\n for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {\n result.push(this.__leavelist[i].node);\n }\n\n return result;\n };\n\n // API:\n // return current node\n Controller.prototype.current = function current() {\n return this.__current.node;\n };\n\n Controller.prototype.__execute = function __execute(callback, element) {\n var previous, result;\n\n result = undefined;\n\n previous = this.__current;\n this.__current = element;\n this.__state = null;\n if (callback) {\n result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node);\n }\n this.__current = previous;\n\n return result;\n };\n\n // API:\n // notify control skip / break\n Controller.prototype.notify = function notify(flag) {\n this.__state = flag;\n };\n\n // API:\n // skip child nodes of current node\n Controller.prototype.skip = function () {\n this.notify(SKIP);\n };\n\n // API:\n // break traversals\n Controller.prototype['break'] = function () {\n this.notify(BREAK);\n };\n\n // API:\n // remove node\n Controller.prototype.remove = function () {\n this.notify(REMOVE);\n };\n\n Controller.prototype.__initialize = function(root, visitor) {\n this.visitor = visitor;\n this.root = root;\n this.__worklist = [];\n this.__leavelist = [];\n this.__current = null;\n this.__state = null;\n this.__fallback = null;\n if (visitor.fallback === 'iteration') {\n this.__fallback = Object.keys;\n } else if (typeof visitor.fallback === 'function') {\n this.__fallback = visitor.fallback;\n }\n\n this.__keys = VisitorKeys;\n if (visitor.keys) {\n this.__keys = Object.assign(Object.create(this.__keys), visitor.keys);\n }\n };\n\n function isNode(node) {\n if (node == null) {\n return false;\n }\n return typeof node === 'object' && typeof node.type === 'string';\n }\n\n function isProperty(nodeType, key) {\n return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key;\n }\n \n function candidateExistsInLeaveList(leavelist, candidate) {\n for (var i = leavelist.length - 1; i >= 0; --i) {\n if (leavelist[i].node === candidate) {\n return true;\n }\n }\n return false;\n }\n\n Controller.prototype.traverse = function traverse(root, visitor) {\n var worklist,\n leavelist,\n element,\n node,\n nodeType,\n ret,\n key,\n current,\n current2,\n candidates,\n candidate,\n sentinel;\n\n this.__initialize(root, visitor);\n\n sentinel = {};\n\n // reference\n worklist = this.__worklist;\n leavelist = this.__leavelist;\n\n // initialize\n worklist.push(new Element(root, null, null, null));\n leavelist.push(new Element(null, null, null, null));\n\n while (worklist.length) {\n element = worklist.pop();\n\n if (element === sentinel) {\n element = leavelist.pop();\n\n ret = this.__execute(visitor.leave, element);\n\n if (this.__state === BREAK || ret === BREAK) {\n return;\n }\n continue;\n }\n\n if (element.node) {\n\n ret = this.__execute(visitor.enter, element);\n\n if (this.__state === BREAK || ret === BREAK) {\n return;\n }\n\n worklist.push(sentinel);\n leavelist.push(element);\n\n if (this.__state === SKIP || ret === SKIP) {\n continue;\n }\n\n node = element.node;\n nodeType = node.type || element.wrap;\n candidates = this.__keys[nodeType];\n if (!candidates) {\n if (this.__fallback) {\n candidates = this.__fallback(node);\n } else {\n throw new Error('Unknown node type ' + nodeType + '.');\n }\n }\n\n current = candidates.length;\n while ((current -= 1) >= 0) {\n key = candidates[current];\n candidate = node[key];\n if (!candidate) {\n continue;\n }\n\n if (Array.isArray(candidate)) {\n current2 = candidate.length;\n while ((current2 -= 1) >= 0) {\n if (!candidate[current2]) {\n continue;\n }\n\n if (candidateExistsInLeaveList(leavelist, candidate[current2])) {\n continue;\n }\n\n if (isProperty(nodeType, candidates[current])) {\n element = new Element(candidate[current2], [key, current2], 'Property', null);\n } else if (isNode(candidate[current2])) {\n element = new Element(candidate[current2], [key, current2], null, null);\n } else {\n continue;\n }\n worklist.push(element);\n }\n } else if (isNode(candidate)) {\n if (candidateExistsInLeaveList(leavelist, candidate)) {\n continue;\n }\n\n worklist.push(new Element(candidate, key, null, null));\n }\n }\n }\n }\n };\n\n Controller.prototype.replace = function replace(root, visitor) {\n var worklist,\n leavelist,\n node,\n nodeType,\n target,\n element,\n current,\n current2,\n candidates,\n candidate,\n sentinel,\n outer,\n key;\n\n function removeElem(element) {\n var i,\n key,\n nextElem,\n parent;\n\n if (element.ref.remove()) {\n // When the reference is an element of an array.\n key = element.ref.key;\n parent = element.ref.parent;\n\n // If removed from array, then decrease following items' keys.\n i = worklist.length;\n while (i--) {\n nextElem = worklist[i];\n if (nextElem.ref && nextElem.ref.parent === parent) {\n if (nextElem.ref.key < key) {\n break;\n }\n --nextElem.ref.key;\n }\n }\n }\n }\n\n this.__initialize(root, visitor);\n\n sentinel = {};\n\n // reference\n worklist = this.__worklist;\n leavelist = this.__leavelist;\n\n // initialize\n outer = {\n root: root\n };\n element = new Element(root, null, null, new Reference(outer, 'root'));\n worklist.push(element);\n leavelist.push(element);\n\n while (worklist.length) {\n element = worklist.pop();\n\n if (element === sentinel) {\n element = leavelist.pop();\n\n target = this.__execute(visitor.leave, element);\n\n // node may be replaced with null,\n // so distinguish between undefined and null in this place\n if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {\n // replace\n element.ref.replace(target);\n }\n\n if (this.__state === REMOVE || target === REMOVE) {\n removeElem(element);\n }\n\n if (this.__state === BREAK || target === BREAK) {\n return outer.root;\n }\n continue;\n }\n\n target = this.__execute(visitor.enter, element);\n\n // node may be replaced with null,\n // so distinguish between undefined and null in this place\n if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {\n // replace\n element.ref.replace(target);\n element.node = target;\n }\n\n if (this.__state === REMOVE || target === REMOVE) {\n removeElem(element);\n element.node = null;\n }\n\n if (this.__state === BREAK || target === BREAK) {\n return outer.root;\n }\n\n // node may be null\n node = element.node;\n if (!node) {\n continue;\n }\n\n worklist.push(sentinel);\n leavelist.push(element);\n\n if (this.__state === SKIP || target === SKIP) {\n continue;\n }\n\n nodeType = node.type || element.wrap;\n candidates = this.__keys[nodeType];\n if (!candidates) {\n if (this.__fallback) {\n candidates = this.__fallback(node);\n } else {\n throw new Error('Unknown node type ' + nodeType + '.');\n }\n }\n\n current = candidates.length;\n while ((current -= 1) >= 0) {\n key = candidates[current];\n candidate = node[key];\n if (!candidate) {\n continue;\n }\n\n if (Array.isArray(candidate)) {\n current2 = candidate.length;\n while ((current2 -= 1) >= 0) {\n if (!candidate[current2]) {\n continue;\n }\n if (isProperty(nodeType, candidates[current])) {\n element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2));\n } else if (isNode(candidate[current2])) {\n element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2));\n } else {\n continue;\n }\n worklist.push(element);\n }\n } else if (isNode(candidate)) {\n worklist.push(new Element(candidate, key, null, new Reference(node, key)));\n }\n }\n }\n\n return outer.root;\n };\n\n function traverse(root, visitor) {\n var controller = new Controller();\n return controller.traverse(root, visitor);\n }\n\n function replace(root, visitor) {\n var controller = new Controller();\n return controller.replace(root, visitor);\n }\n\n function extendCommentRange(comment, tokens) {\n var target;\n\n target = upperBound(tokens, function search(token) {\n return token.range[0] > comment.range[0];\n });\n\n comment.extendedRange = [comment.range[0], comment.range[1]];\n\n if (target !== tokens.length) {\n comment.extendedRange[1] = tokens[target].range[0];\n }\n\n target -= 1;\n if (target >= 0) {\n comment.extendedRange[0] = tokens[target].range[1];\n }\n\n return comment;\n }\n\n function attachComments(tree, providedComments, tokens) {\n // At first, we should calculate extended comment ranges.\n var comments = [], comment, len, i, cursor;\n\n if (!tree.range) {\n throw new Error('attachComments needs range information');\n }\n\n // tokens array is empty, we attach comments to tree as 'leadingComments'\n if (!tokens.length) {\n if (providedComments.length) {\n for (i = 0, len = providedComments.length; i < len; i += 1) {\n comment = deepCopy(providedComments[i]);\n comment.extendedRange = [0, tree.range[0]];\n comments.push(comment);\n }\n tree.leadingComments = comments;\n }\n return tree;\n }\n\n for (i = 0, len = providedComments.length; i < len; i += 1) {\n comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens));\n }\n\n // This is based on John Freeman's implementation.\n cursor = 0;\n traverse(tree, {\n enter: function (node) {\n var comment;\n\n while (cursor < comments.length) {\n comment = comments[cursor];\n if (comment.extendedRange[1] > node.range[0]) {\n break;\n }\n\n if (comment.extendedRange[1] === node.range[0]) {\n if (!node.leadingComments) {\n node.leadingComments = [];\n }\n node.leadingComments.push(comment);\n comments.splice(cursor, 1);\n } else {\n cursor += 1;\n }\n }\n\n // already out of owned node\n if (cursor === comments.length) {\n return VisitorOption.Break;\n }\n\n if (comments[cursor].extendedRange[0] > node.range[1]) {\n return VisitorOption.Skip;\n }\n }\n });\n\n cursor = 0;\n traverse(tree, {\n leave: function (node) {\n var comment;\n\n while (cursor < comments.length) {\n comment = comments[cursor];\n if (node.range[1] < comment.extendedRange[0]) {\n break;\n }\n\n if (node.range[1] === comment.extendedRange[0]) {\n if (!node.trailingComments) {\n node.trailingComments = [];\n }\n node.trailingComments.push(comment);\n comments.splice(cursor, 1);\n } else {\n cursor += 1;\n }\n }\n\n // already out of owned node\n if (cursor === comments.length) {\n return VisitorOption.Break;\n }\n\n if (comments[cursor].extendedRange[0] > node.range[1]) {\n return VisitorOption.Skip;\n }\n }\n });\n\n return tree;\n }\n\n exports.Syntax = Syntax;\n exports.traverse = traverse;\n exports.replace = replace;\n exports.attachComments = attachComments;\n exports.VisitorKeys = VisitorKeys;\n exports.VisitorOption = VisitorOption;\n exports.Controller = Controller;\n exports.cloneEnvironment = function () { return clone({}); };\n\n return exports;\n}(exports));\n/* vim: set sw=4 ts=4 et tw=80 : */\n","/*\n * Generated by PEG.js 0.10.0.\n *\n * http://pegjs.org/\n */\n(function(root, factory) {\n if (typeof define === \"function\" && define.amd) {\n define([], factory);\n } else if (typeof module === \"object\" && module.exports) {\n module.exports = factory();\n }\n})(this, function() {\n \"use strict\";\n\n function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }\n\n function peg$SyntaxError(message, expected, found, location) {\n this.message = message;\n this.expected = expected;\n this.found = found;\n this.location = location;\n this.name = \"SyntaxError\";\n\n if (typeof Error.captureStackTrace === \"function\") {\n Error.captureStackTrace(this, peg$SyntaxError);\n }\n }\n\n peg$subclass(peg$SyntaxError, Error);\n\n peg$SyntaxError.buildMessage = function(expected, found) {\n var DESCRIBE_EXPECTATION_FNS = {\n literal: function(expectation) {\n return \"\\\"\" + literalEscape(expectation.text) + \"\\\"\";\n },\n\n \"class\": function(expectation) {\n var escapedParts = \"\",\n i;\n\n for (i = 0; i < expectation.parts.length; i++) {\n escapedParts += expectation.parts[i] instanceof Array\n ? classEscape(expectation.parts[i][0]) + \"-\" + classEscape(expectation.parts[i][1])\n : classEscape(expectation.parts[i]);\n }\n\n return \"[\" + (expectation.inverted ? \"^\" : \"\") + escapedParts + \"]\";\n },\n\n any: function(expectation) {\n return \"any character\";\n },\n\n end: function(expectation) {\n return \"end of input\";\n },\n\n other: function(expectation) {\n return expectation.description;\n }\n };\n\n function hex(ch) {\n return ch.charCodeAt(0).toString(16).toUpperCase();\n }\n\n function literalEscape(s) {\n return s\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/\\0/g, '\\\\0')\n .replace(/\\t/g, '\\\\t')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/[\\x00-\\x0F]/g, function(ch) { return '\\\\x0' + hex(ch); })\n .replace(/[\\x10-\\x1F\\x7F-\\x9F]/g, function(ch) { return '\\\\x' + hex(ch); });\n }\n\n function classEscape(s) {\n return s\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\\]/g, '\\\\]')\n .replace(/\\^/g, '\\\\^')\n .replace(/-/g, '\\\\-')\n .replace(/\\0/g, '\\\\0')\n .replace(/\\t/g, '\\\\t')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/[\\x00-\\x0F]/g, function(ch) { return '\\\\x0' + hex(ch); })\n .replace(/[\\x10-\\x1F\\x7F-\\x9F]/g, function(ch) { return '\\\\x' + hex(ch); });\n }\n\n function describeExpectation(expectation) {\n return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation);\n }\n\n function describeExpected(expected) {\n var descriptions = new Array(expected.length),\n i, j;\n\n for (i = 0; i < expected.length; i++) {\n descriptions[i] = describeExpectation(expected[i]);\n }\n\n descriptions.sort();\n\n if (descriptions.length > 0) {\n for (i = 1, j = 1; i < descriptions.length; i++) {\n if (descriptions[i - 1] !== descriptions[i]) {\n descriptions[j] = descriptions[i];\n j++;\n }\n }\n descriptions.length = j;\n }\n\n switch (descriptions.length) {\n case 1:\n return descriptions[0];\n\n case 2:\n return descriptions[0] + \" or \" + descriptions[1];\n\n default:\n return descriptions.slice(0, -1).join(\", \")\n + \", or \"\n + descriptions[descriptions.length - 1];\n }\n }\n\n function describeFound(found) {\n return found ? \"\\\"\" + literalEscape(found) + \"\\\"\" : \"end of input\";\n }\n\n return \"Expected \" + describeExpected(expected) + \" but \" + describeFound(found) + \" found.\";\n };\n\n function peg$parse(input, options) {\n options = options !== void 0 ? options : {};\n\n var peg$FAILED = {},\n\n peg$startRuleFunctions = { start: peg$parsestart },\n peg$startRuleFunction = peg$parsestart,\n\n peg$c0 = function(ss) {\n return ss.length === 1 ? ss[0] : { type: 'matches', selectors: ss };\n },\n peg$c1 = function() { return void 0; },\n peg$c2 = \" \",\n peg$c3 = peg$literalExpectation(\" \", false),\n peg$c4 = /^[^ [\\],():#!=><~+.]/,\n peg$c5 = peg$classExpectation([\" \", \"[\", \"]\", \",\", \"(\", \")\", \":\", \"#\", \"!\", \"=\", \">\", \"<\", \"~\", \"+\", \".\"], true, false),\n peg$c6 = function(i) { return i.join(''); },\n peg$c7 = \">\",\n peg$c8 = peg$literalExpectation(\">\", false),\n peg$c9 = function() { return 'child'; },\n peg$c10 = \"~\",\n peg$c11 = peg$literalExpectation(\"~\", false),\n peg$c12 = function() { return 'sibling'; },\n peg$c13 = \"+\",\n peg$c14 = peg$literalExpectation(\"+\", false),\n peg$c15 = function() { return 'adjacent'; },\n peg$c16 = function() { return 'descendant'; },\n peg$c17 = \",\",\n peg$c18 = peg$literalExpectation(\",\", false),\n peg$c19 = function(s, ss) {\n return [s].concat(ss.map(function (s) { return s[3]; }));\n },\n peg$c20 = function(op, s) {\n if (!op) return s;\n return { type: op, left: { type: 'exactNode' }, right: s };\n },\n peg$c21 = function(a, ops) {\n return ops.reduce(function (memo, rhs) {\n return { type: rhs[0], left: memo, right: rhs[1] };\n }, a);\n },\n peg$c22 = \"!\",\n peg$c23 = peg$literalExpectation(\"!\", false),\n peg$c24 = function(subject, as) {\n const b = as.length === 1 ? as[0] : { type: 'compound', selectors: as };\n if(subject) b.subject = true;\n return b;\n },\n peg$c25 = \"*\",\n peg$c26 = peg$literalExpectation(\"*\", false),\n peg$c27 = function(a) { return { type: 'wildcard', value: a }; },\n peg$c28 = \"#\",\n peg$c29 = peg$literalExpectation(\"#\", false),\n peg$c30 = function(i) { return { type: 'identifier', value: i }; },\n peg$c31 = \"[\",\n peg$c32 = peg$literalExpectation(\"[\", false),\n peg$c33 = \"]\",\n peg$c34 = peg$literalExpectation(\"]\", false),\n peg$c35 = function(v) { return v; },\n peg$c36 = /^[>\", \"<\", \"!\"], false, false),\n peg$c38 = \"=\",\n peg$c39 = peg$literalExpectation(\"=\", false),\n peg$c40 = function(a) { return (a || '') + '='; },\n peg$c41 = /^[><]/,\n peg$c42 = peg$classExpectation([\">\", \"<\"], false, false),\n peg$c43 = \".\",\n peg$c44 = peg$literalExpectation(\".\", false),\n peg$c45 = function(a, as) {\n return [].concat.apply([a], as).join('');\n },\n peg$c46 = function(name, op, value) {\n return { type: 'attribute', name: name, operator: op, value: value };\n },\n peg$c47 = function(name) { return { type: 'attribute', name: name }; },\n peg$c48 = \"\\\"\",\n peg$c49 = peg$literalExpectation(\"\\\"\", false),\n peg$c50 = /^[^\\\\\"]/,\n peg$c51 = peg$classExpectation([\"\\\\\", \"\\\"\"], true, false),\n peg$c52 = \"\\\\\",\n peg$c53 = peg$literalExpectation(\"\\\\\", false),\n peg$c54 = peg$anyExpectation(),\n peg$c55 = function(a, b) { return a + b; },\n peg$c56 = function(d) {\n return { type: 'literal', value: strUnescape(d.join('')) };\n },\n peg$c57 = \"'\",\n peg$c58 = peg$literalExpectation(\"'\", false),\n peg$c59 = /^[^\\\\']/,\n peg$c60 = peg$classExpectation([\"\\\\\", \"'\"], true, false),\n peg$c61 = /^[0-9]/,\n peg$c62 = peg$classExpectation([[\"0\", \"9\"]], false, false),\n peg$c63 = function(a, b) {\n // Can use `a.flat().join('')` once supported\n const leadingDecimals = a ? [].concat.apply([], a).join('') : '';\n return { type: 'literal', value: parseFloat(leadingDecimals + b.join('')) };\n },\n peg$c64 = function(i) { return { type: 'literal', value: i }; },\n peg$c65 = \"type(\",\n peg$c66 = peg$literalExpectation(\"type(\", false),\n peg$c67 = /^[^ )]/,\n peg$c68 = peg$classExpectation([\" \", \")\"], true, false),\n peg$c69 = \")\",\n peg$c70 = peg$literalExpectation(\")\", false),\n peg$c71 = function(t) { return { type: 'type', value: t.join('') }; },\n peg$c72 = /^[imsu]/,\n peg$c73 = peg$classExpectation([\"i\", \"m\", \"s\", \"u\"], false, false),\n peg$c74 = \"/\",\n peg$c75 = peg$literalExpectation(\"/\", false),\n peg$c76 = function(pattern, flgs) {\n return {\n type: 'regexp', value: new RegExp(pattern.join(''), flgs ? flgs.join('') : '')\n };\n },\n peg$c77 = /^[^\\]\\\\]/,\n peg$c78 = peg$classExpectation([\"]\", \"\\\\\"], true, false),\n peg$c79 = function(cs) { return '[' + cs.join('') + ']'; },\n peg$c80 = function(a) { return '\\\\' + a; },\n peg$c81 = /^[^\\/\\\\[]/,\n peg$c82 = peg$classExpectation([\"/\", \"\\\\\", \"[\"], true, false),\n peg$c83 = function(cs) { return cs.join(''); },\n peg$c84 = function(i, is) {\n return { type: 'field', name: is.reduce(function(memo, p){ return memo + p[0] + p[1]; }, i)};\n },\n peg$c85 = \":not(\",\n peg$c86 = peg$literalExpectation(\":not(\", false),\n peg$c87 = function(ss) { return { type: 'not', selectors: ss }; },\n peg$c88 = \":matches(\",\n peg$c89 = peg$literalExpectation(\":matches(\", false),\n peg$c90 = function(ss) { return { type: 'matches', selectors: ss }; },\n peg$c91 = \":is(\",\n peg$c92 = peg$literalExpectation(\":is(\", false),\n peg$c93 = \":has(\",\n peg$c94 = peg$literalExpectation(\":has(\", false),\n peg$c95 = function(ss) { return { type: 'has', selectors: ss }; },\n peg$c96 = \":first-child\",\n peg$c97 = peg$literalExpectation(\":first-child\", false),\n peg$c98 = function() { return nth(1); },\n peg$c99 = \":last-child\",\n peg$c100 = peg$literalExpectation(\":last-child\", false),\n peg$c101 = function() { return nthLast(1); },\n peg$c102 = \":nth-child(\",\n peg$c103 = peg$literalExpectation(\":nth-child(\", false),\n peg$c104 = function(n) { return nth(parseInt(n.join(''), 10)); },\n peg$c105 = \":nth-last-child(\",\n peg$c106 = peg$literalExpectation(\":nth-last-child(\", false),\n peg$c107 = function(n) { return nthLast(parseInt(n.join(''), 10)); },\n peg$c108 = \":\",\n peg$c109 = peg$literalExpectation(\":\", false),\n peg$c110 = function(c) {\n return { type: 'class', name: c };\n },\n\n peg$currPos = 0,\n peg$savedPos = 0,\n peg$posDetailsCache = [{ line: 1, column: 1 }],\n peg$maxFailPos = 0,\n peg$maxFailExpected = [],\n peg$silentFails = 0,\n\n peg$resultsCache = {},\n\n peg$result;\n\n if (\"startRule\" in options) {\n if (!(options.startRule in peg$startRuleFunctions)) {\n throw new Error(\"Can't start parsing from rule \\\"\" + options.startRule + \"\\\".\");\n }\n\n peg$startRuleFunction = peg$startRuleFunctions[options.startRule];\n }\n\n function text() {\n return input.substring(peg$savedPos, peg$currPos);\n }\n\n function location() {\n return peg$computeLocation(peg$savedPos, peg$currPos);\n }\n\n function expected(description, location) {\n location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos)\n\n throw peg$buildStructuredError(\n [peg$otherExpectation(description)],\n input.substring(peg$savedPos, peg$currPos),\n location\n );\n }\n\n function error(message, location) {\n location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos)\n\n throw peg$buildSimpleError(message, location);\n }\n\n function peg$literalExpectation(text, ignoreCase) {\n return { type: \"literal\", text: text, ignoreCase: ignoreCase };\n }\n\n function peg$classExpectation(parts, inverted, ignoreCase) {\n return { type: \"class\", parts: parts, inverted: inverted, ignoreCase: ignoreCase };\n }\n\n function peg$anyExpectation() {\n return { type: \"any\" };\n }\n\n function peg$endExpectation() {\n return { type: \"end\" };\n }\n\n function peg$otherExpectation(description) {\n return { type: \"other\", description: description };\n }\n\n function peg$computePosDetails(pos) {\n var details = peg$posDetailsCache[pos], p;\n\n if (details) {\n return details;\n } else {\n p = pos - 1;\n while (!peg$posDetailsCache[p]) {\n p--;\n }\n\n details = peg$posDetailsCache[p];\n details = {\n line: details.line,\n column: details.column\n };\n\n while (p < pos) {\n if (input.charCodeAt(p) === 10) {\n details.line++;\n details.column = 1;\n } else {\n details.column++;\n }\n\n p++;\n }\n\n peg$posDetailsCache[pos] = details;\n return details;\n }\n }\n\n function peg$computeLocation(startPos, endPos) {\n var startPosDetails = peg$computePosDetails(startPos),\n endPosDetails = peg$computePosDetails(endPos);\n\n return {\n start: {\n offset: startPos,\n line: startPosDetails.line,\n column: startPosDetails.column\n },\n end: {\n offset: endPos,\n line: endPosDetails.line,\n column: endPosDetails.column\n }\n };\n }\n\n function peg$fail(expected) {\n if (peg$currPos < peg$maxFailPos) { return; }\n\n if (peg$currPos > peg$maxFailPos) {\n peg$maxFailPos = peg$currPos;\n peg$maxFailExpected = [];\n }\n\n peg$maxFailExpected.push(expected);\n }\n\n function peg$buildSimpleError(message, location) {\n return new peg$SyntaxError(message, null, null, location);\n }\n\n function peg$buildStructuredError(expected, found, location) {\n return new peg$SyntaxError(\n peg$SyntaxError.buildMessage(expected, found),\n expected,\n found,\n location\n );\n }\n\n function peg$parsestart() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 36 + 0,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n s2 = peg$parseselectors();\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c0(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c1();\n }\n s0 = s1;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parse_() {\n var s0, s1;\n\n var key = peg$currPos * 36 + 1,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = [];\n if (input.charCodeAt(peg$currPos) === 32) {\n s1 = peg$c2;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c3); }\n }\n while (s1 !== peg$FAILED) {\n s0.push(s1);\n if (input.charCodeAt(peg$currPos) === 32) {\n s1 = peg$c2;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c3); }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseidentifierName() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 2,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = [];\n if (peg$c4.test(input.charAt(peg$currPos))) {\n s2 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c5); }\n }\n if (s2 !== peg$FAILED) {\n while (s2 !== peg$FAILED) {\n s1.push(s2);\n if (peg$c4.test(input.charAt(peg$currPos))) {\n s2 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c5); }\n }\n }\n } else {\n s1 = peg$FAILED;\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c6(s1);\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsebinaryOp() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 36 + 3,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 62) {\n s2 = peg$c7;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c8); }\n }\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c9();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 126) {\n s2 = peg$c10;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c11); }\n }\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c12();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parse_();\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 43) {\n s2 = peg$c13;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c14); }\n }\n if (s2 !== peg$FAILED) {\n s3 = peg$parse_();\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c15();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 32) {\n s1 = peg$c2;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c3); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c16();\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsehasSelectors() {\n var s0, s1, s2, s3, s4, s5, s6, s7;\n\n var key = peg$currPos * 36 + 4,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parsehasSelector();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parsehasSelector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parsehasSelector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c19(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseselectors() {\n var s0, s1, s2, s3, s4, s5, s6, s7;\n\n var key = peg$currPos * 36 + 5,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseselector();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parseselector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 44) {\n s5 = peg$c17;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c18); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parse_();\n if (s6 !== peg$FAILED) {\n s7 = peg$parseselector();\n if (s7 !== peg$FAILED) {\n s4 = [s4, s5, s6, s7];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c19(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsehasSelector() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 6,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parsebinaryOp();\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseselector();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c20(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseselector() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 7,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parsesequence();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n s4 = peg$parsebinaryOp();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsesequence();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n s4 = peg$parsebinaryOp();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsesequence();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c21(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsesequence() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 36 + 8,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 33) {\n s1 = peg$c22;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c23); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$parseatom();\n if (s3 !== peg$FAILED) {\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$parseatom();\n }\n } else {\n s2 = peg$FAILED;\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c24(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseatom() {\n var s0;\n\n var key = peg$currPos * 36 + 9,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$parsewildcard();\n if (s0 === peg$FAILED) {\n s0 = peg$parseidentifier();\n if (s0 === peg$FAILED) {\n s0 = peg$parseattr();\n if (s0 === peg$FAILED) {\n s0 = peg$parsefield();\n if (s0 === peg$FAILED) {\n s0 = peg$parsenegation();\n if (s0 === peg$FAILED) {\n s0 = peg$parsematches();\n if (s0 === peg$FAILED) {\n s0 = peg$parseis();\n if (s0 === peg$FAILED) {\n s0 = peg$parsehas();\n if (s0 === peg$FAILED) {\n s0 = peg$parsefirstChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parselastChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parsenthChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parsenthLastChild();\n if (s0 === peg$FAILED) {\n s0 = peg$parseclass();\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsewildcard() {\n var s0, s1;\n\n var key = peg$currPos * 36 + 10,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 42) {\n s1 = peg$c25;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c26); }\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c27(s1);\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseidentifier() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 11,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 35) {\n s1 = peg$c28;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c29); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseidentifierName();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c30(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattr() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 12,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 91) {\n s1 = peg$c31;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c32); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseattrValue();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 93) {\n s5 = peg$c33;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c34); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c35(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrOps() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 13,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (peg$c36.test(input.charAt(peg$currPos))) {\n s1 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c37); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 61) {\n s2 = peg$c38;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c39); }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c40(s1);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n if (peg$c41.test(input.charAt(peg$currPos))) {\n s0 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s0 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c42); }\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrEqOps() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 14,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 33) {\n s1 = peg$c22;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c23); }\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 61) {\n s2 = peg$c38;\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c39); }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c40(s1);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrName() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 15,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseidentifierName();\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s4 = peg$c43;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s4 !== peg$FAILED) {\n s5 = peg$parseidentifierName();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s4 = peg$c43;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s4 !== peg$FAILED) {\n s5 = peg$parseidentifierName();\n if (s5 !== peg$FAILED) {\n s4 = [s4, s5];\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c45(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseattrValue() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 16,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseattrName();\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseattrEqOps();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsetype();\n if (s5 === peg$FAILED) {\n s5 = peg$parseregex();\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c46(s1, s3, s5);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parseattrName();\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseattrOps();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n s5 = peg$parsestring();\n if (s5 === peg$FAILED) {\n s5 = peg$parsenumber();\n if (s5 === peg$FAILED) {\n s5 = peg$parsepath();\n }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c46(s1, s3, s5);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n s1 = peg$parseattrName();\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c47(s1);\n }\n s0 = s1;\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsestring() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 17,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 34) {\n s1 = peg$c48;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c49); }\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c50.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c51); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c50.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c51); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 34) {\n s3 = peg$c48;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c49); }\n }\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c56(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n if (s0 === peg$FAILED) {\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 39) {\n s1 = peg$c57;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c58); }\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c59.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c60); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c59.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c60); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s4 = peg$c52;\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s4 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s5 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s3;\n s4 = peg$c55(s4, s5);\n s3 = s4;\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n } else {\n peg$currPos = s3;\n s3 = peg$FAILED;\n }\n }\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 39) {\n s3 = peg$c57;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c58); }\n }\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c56(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenumber() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 36 + 18,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$currPos;\n s2 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 46) {\n s3 = peg$c43;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s3 !== peg$FAILED) {\n s2 = [s2, s3];\n s1 = s2;\n } else {\n peg$currPos = s1;\n s1 = peg$FAILED;\n }\n } else {\n peg$currPos = s1;\n s1 = peg$FAILED;\n }\n if (s1 === peg$FAILED) {\n s1 = null;\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n if (s3 !== peg$FAILED) {\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n } else {\n s2 = peg$FAILED;\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c63(s1, s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsepath() {\n var s0, s1;\n\n var key = peg$currPos * 36 + 19,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = peg$parseidentifierName();\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c64(s1);\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsetype() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 20,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 5) === peg$c65) {\n s1 = peg$c65;\n peg$currPos += 5;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c66); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = [];\n if (peg$c67.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c68); }\n }\n if (s4 !== peg$FAILED) {\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n if (peg$c67.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c68); }\n }\n }\n } else {\n s3 = peg$FAILED;\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c71(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseflags() {\n var s0, s1;\n\n var key = peg$currPos * 36 + 21,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = [];\n if (peg$c72.test(input.charAt(peg$currPos))) {\n s1 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c73); }\n }\n if (s1 !== peg$FAILED) {\n while (s1 !== peg$FAILED) {\n s0.push(s1);\n if (peg$c72.test(input.charAt(peg$currPos))) {\n s1 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c73); }\n }\n }\n } else {\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseregex() {\n var s0, s1, s2, s3, s4;\n\n var key = peg$currPos * 36 + 22,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 47) {\n s1 = peg$c74;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c75); }\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n s3 = peg$parsere_character_class();\n if (s3 === peg$FAILED) {\n s3 = peg$parsere_escape();\n if (s3 === peg$FAILED) {\n s3 = peg$parsere_chars();\n }\n }\n if (s3 !== peg$FAILED) {\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n s3 = peg$parsere_character_class();\n if (s3 === peg$FAILED) {\n s3 = peg$parsere_escape();\n if (s3 === peg$FAILED) {\n s3 = peg$parsere_chars();\n }\n }\n }\n } else {\n s2 = peg$FAILED;\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 47) {\n s3 = peg$c74;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c75); }\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parseflags();\n if (s4 === peg$FAILED) {\n s4 = null;\n }\n if (s4 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c76(s2, s4);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsere_character_class() {\n var s0, s1, s2, s3;\n\n var key = peg$currPos * 36 + 23,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 91) {\n s1 = peg$c31;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c32); }\n }\n if (s1 !== peg$FAILED) {\n s2 = [];\n if (peg$c77.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c78); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$parsere_escape();\n }\n if (s3 !== peg$FAILED) {\n while (s3 !== peg$FAILED) {\n s2.push(s3);\n if (peg$c77.test(input.charAt(peg$currPos))) {\n s3 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c78); }\n }\n if (s3 === peg$FAILED) {\n s3 = peg$parsere_escape();\n }\n }\n } else {\n s2 = peg$FAILED;\n }\n if (s2 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 93) {\n s3 = peg$c33;\n peg$currPos++;\n } else {\n s3 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c34); }\n }\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c79(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsere_escape() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 24,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 92) {\n s1 = peg$c52;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c53); }\n }\n if (s1 !== peg$FAILED) {\n if (input.length > peg$currPos) {\n s2 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c54); }\n }\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c80(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsere_chars() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 25,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n s1 = [];\n if (peg$c81.test(input.charAt(peg$currPos))) {\n s2 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c82); }\n }\n if (s2 !== peg$FAILED) {\n while (s2 !== peg$FAILED) {\n s1.push(s2);\n if (peg$c81.test(input.charAt(peg$currPos))) {\n s2 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s2 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c82); }\n }\n }\n } else {\n s1 = peg$FAILED;\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c83(s1);\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsefield() {\n var s0, s1, s2, s3, s4, s5, s6;\n\n var key = peg$currPos * 36 + 26,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s1 = peg$c43;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseidentifierName();\n if (s2 !== peg$FAILED) {\n s3 = [];\n s4 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s5 = peg$c43;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parseidentifierName();\n if (s6 !== peg$FAILED) {\n s5 = [s5, s6];\n s4 = s5;\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n s4 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 46) {\n s5 = peg$c43;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c44); }\n }\n if (s5 !== peg$FAILED) {\n s6 = peg$parseidentifierName();\n if (s6 !== peg$FAILED) {\n s5 = [s5, s6];\n s4 = s5;\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n } else {\n peg$currPos = s4;\n s4 = peg$FAILED;\n }\n }\n if (s3 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c84(s2, s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenegation() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 27,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 5) === peg$c85) {\n s1 = peg$c85;\n peg$currPos += 5;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c86); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseselectors();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c87(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsematches() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 28,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 9) === peg$c88) {\n s1 = peg$c88;\n peg$currPos += 9;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c89); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseselectors();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c90(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseis() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 29,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 4) === peg$c91) {\n s1 = peg$c91;\n peg$currPos += 4;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c92); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parseselectors();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c90(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsehas() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 30,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 5) === peg$c93) {\n s1 = peg$c93;\n peg$currPos += 5;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c94); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = peg$parsehasSelectors();\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c95(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsefirstChild() {\n var s0, s1;\n\n var key = peg$currPos * 36 + 31,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 12) === peg$c96) {\n s1 = peg$c96;\n peg$currPos += 12;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c97); }\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c98();\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parselastChild() {\n var s0, s1;\n\n var key = peg$currPos * 36 + 32,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 11) === peg$c99) {\n s1 = peg$c99;\n peg$currPos += 11;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c100); }\n }\n if (s1 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c101();\n }\n s0 = s1;\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenthChild() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 33,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 11) === peg$c102) {\n s1 = peg$c102;\n peg$currPos += 11;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c103); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n if (s4 !== peg$FAILED) {\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n } else {\n s3 = peg$FAILED;\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c104(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parsenthLastChild() {\n var s0, s1, s2, s3, s4, s5;\n\n var key = peg$currPos * 36 + 34,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.substr(peg$currPos, 16) === peg$c105) {\n s1 = peg$c105;\n peg$currPos += 16;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c106); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parse_();\n if (s2 !== peg$FAILED) {\n s3 = [];\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n if (s4 !== peg$FAILED) {\n while (s4 !== peg$FAILED) {\n s3.push(s4);\n if (peg$c61.test(input.charAt(peg$currPos))) {\n s4 = input.charAt(peg$currPos);\n peg$currPos++;\n } else {\n s4 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c62); }\n }\n }\n } else {\n s3 = peg$FAILED;\n }\n if (s3 !== peg$FAILED) {\n s4 = peg$parse_();\n if (s4 !== peg$FAILED) {\n if (input.charCodeAt(peg$currPos) === 41) {\n s5 = peg$c69;\n peg$currPos++;\n } else {\n s5 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c70); }\n }\n if (s5 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c107(s3);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n function peg$parseclass() {\n var s0, s1, s2;\n\n var key = peg$currPos * 36 + 35,\n cached = peg$resultsCache[key];\n\n if (cached) {\n peg$currPos = cached.nextPos;\n\n return cached.result;\n }\n\n s0 = peg$currPos;\n if (input.charCodeAt(peg$currPos) === 58) {\n s1 = peg$c108;\n peg$currPos++;\n } else {\n s1 = peg$FAILED;\n if (peg$silentFails === 0) { peg$fail(peg$c109); }\n }\n if (s1 !== peg$FAILED) {\n s2 = peg$parseidentifierName();\n if (s2 !== peg$FAILED) {\n peg$savedPos = s0;\n s1 = peg$c110(s2);\n s0 = s1;\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n } else {\n peg$currPos = s0;\n s0 = peg$FAILED;\n }\n\n peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 };\n\n return s0;\n }\n\n\n function nth(n) { return { type: 'nth-child', index: { type: 'literal', value: n } }; }\n function nthLast(n) { return { type: 'nth-last-child', index: { type: 'literal', value: n } }; }\n function strUnescape(s) {\n return s.replace(/\\\\(.)/g, function(match, ch) {\n switch(ch) {\n case 'b': return '\\b';\n case 'f': return '\\f';\n case 'n': return '\\n';\n case 'r': return '\\r';\n case 't': return '\\t';\n case 'v': return '\\v';\n default: return ch;\n }\n });\n }\n\n\n peg$result = peg$startRuleFunction();\n\n if (peg$result !== peg$FAILED && peg$currPos === input.length) {\n return peg$result;\n } else {\n if (peg$result !== peg$FAILED && peg$currPos < input.length) {\n peg$fail(peg$endExpectation());\n }\n\n throw peg$buildStructuredError(\n peg$maxFailExpected,\n peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null,\n peg$maxFailPos < input.length\n ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1)\n : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)\n );\n }\n }\n\n return {\n SyntaxError: peg$SyntaxError,\n parse: peg$parse\n };\n});\n","/* vim: set sw=4 sts=4 : */\nimport estraverse from 'estraverse';\nimport parser from './parser.js';\n\n/**\n* @typedef {\"LEFT_SIDE\"|\"RIGHT_SIDE\"} Side\n*/\n\nconst LEFT_SIDE = 'LEFT_SIDE';\nconst RIGHT_SIDE = 'RIGHT_SIDE';\n\n/**\n * @external AST\n * @see https://esprima.readthedocs.io/en/latest/syntax-tree-format.html\n */\n\n/**\n * One of the rules of `grammar.pegjs`\n * @typedef {PlainObject} SelectorAST\n * @see grammar.pegjs\n*/\n\n/**\n * The `sequence` production of `grammar.pegjs`\n * @typedef {PlainObject} SelectorSequenceAST\n*/\n\n/**\n * Get the value of a property which may be multiple levels down\n * in the object.\n * @param {?PlainObject} obj\n * @param {string[]} keys\n * @returns {undefined|boolean|string|number|external:AST}\n */\nfunction getPath(obj, keys) {\n for (let i = 0; i < keys.length; ++i) {\n if (obj == null) { return obj; }\n obj = obj[keys[i]];\n }\n return obj;\n}\n\n/**\n * Determine whether `node` can be reached by following `path`,\n * starting at `ancestor`.\n * @param {?external:AST} node\n * @param {?external:AST} ancestor\n * @param {string[]} path\n * @param {Integer} fromPathIndex\n * @returns {boolean}\n */\nfunction inPath(node, ancestor, path, fromPathIndex) {\n let current = ancestor;\n for (let i = fromPathIndex; i < path.length; ++i) {\n if (current == null) {\n return false;\n }\n const field = current[path[i]];\n if (Array.isArray(field)) {\n for (let k = 0; k < field.length; ++k) {\n if (inPath(node, field[k], path, i + 1)) {\n return true;\n }\n }\n return false;\n }\n current = field;\n }\n return node === current;\n}\n\n/**\n * A generated matcher function for a selector.\n * @callback SelectorMatcher\n * @param {?SelectorAST} selector\n * @param {external:AST[]} [ancestry=[]]\n * @param {ESQueryOptions} [options]\n * @returns {void}\n*/\n\n/**\n * A WeakMap for holding cached matcher functions for selectors.\n * @type {WeakMap}\n*/\nconst MATCHER_CACHE = typeof WeakMap === 'function' ? new WeakMap : null;\n\n/**\n * Look up a matcher function for `selector` in the cache.\n * If it does not exist, generate it with `generateMatcher` and add it to the cache.\n * In engines without WeakMap, the caching is skipped and matchers are generated with every call.\n * @param {?SelectorAST} selector\n * @returns {SelectorMatcher}\n */\nfunction getMatcher(selector) {\n if (selector == null) {\n return () => true;\n }\n\n if (MATCHER_CACHE != null) {\n let matcher = MATCHER_CACHE.get(selector);\n if (matcher != null) {\n return matcher;\n }\n matcher = generateMatcher(selector);\n MATCHER_CACHE.set(selector, matcher);\n return matcher;\n }\n\n return generateMatcher(selector);\n}\n\n/**\n * Create a matcher function for `selector`,\n * @param {?SelectorAST} selector\n * @returns {SelectorMatcher}\n */\nfunction generateMatcher(selector) {\n switch(selector.type) {\n case 'wildcard':\n return () => true;\n\n case 'identifier': {\n const value = selector.value.toLowerCase();\n return (node, ancestry, options) => {\n const nodeTypeKey = (options && options.nodeTypeKey) || 'type';\n return value === node[nodeTypeKey].toLowerCase();\n };\n }\n\n case 'exactNode':\n return (node, ancestry) => {\n return ancestry.length === 0;\n };\n\n case 'field': {\n const path = selector.name.split('.');\n return (node, ancestry) => {\n const ancestor = ancestry[path.length - 1];\n return inPath(node, ancestor, path, 0);\n };\n }\n\n case 'matches': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n for (let i = 0; i < matchers.length; ++i) {\n if (matchers[i](node, ancestry, options)) { return true; }\n }\n return false;\n };\n }\n\n case 'compound': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n for (let i = 0; i < matchers.length; ++i) {\n if (!matchers[i](node, ancestry, options)) { return false; }\n }\n return true;\n };\n }\n\n case 'not': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n for (let i = 0; i < matchers.length; ++i) {\n if (matchers[i](node, ancestry, options)) { return false; }\n }\n return true;\n };\n }\n\n case 'has': {\n const matchers = selector.selectors.map(getMatcher);\n return (node, ancestry, options) => {\n let result = false;\n\n const a = [];\n estraverse.traverse(node, {\n enter (node, parent) {\n if (parent != null) { a.unshift(parent); }\n\n for (let i = 0; i < matchers.length; ++i) {\n if (matchers[i](node, a, options)) {\n result = true;\n this.break();\n return;\n }\n }\n },\n leave () { a.shift(); },\n keys: options && options.visitorKeys,\n fallback: options && options.fallback || 'iteration'\n });\n\n return result;\n };\n }\n\n case 'child': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) => {\n if (ancestry.length > 0 && right(node, ancestry, options)) {\n return left(ancestry[0], ancestry.slice(1), options);\n }\n return false;\n };\n }\n\n case 'descendant': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) => {\n if (right(node, ancestry, options)) {\n for (let i = 0, l = ancestry.length; i < l; ++i) {\n if (left(ancestry[i], ancestry.slice(i + 1), options)) {\n return true;\n }\n }\n }\n return false;\n };\n }\n\n case 'attribute': {\n const path = selector.name.split('.');\n switch (selector.operator) {\n case void 0:\n return (node) => getPath(node, path) != null;\n case '=':\n switch (selector.value.type) {\n case 'regexp':\n return (node) => {\n const p = getPath(node, path);\n return typeof p === 'string' && selector.value.value.test(p);\n };\n case 'literal': {\n const literal = `${selector.value.value}`;\n return (node) => literal === `${getPath(node, path)}`;\n }\n case 'type':\n return (node) => selector.value.value === typeof getPath(node, path);\n }\n throw new Error(`Unknown selector value type: ${selector.value.type}`);\n case '!=':\n switch (selector.value.type) {\n case 'regexp':\n return (node) => !selector.value.value.test(getPath(node, path));\n case 'literal': {\n const literal = `${selector.value.value}`;\n return (node) => literal !== `${getPath(node, path)}`;\n }\n case 'type':\n return (node) => selector.value.value !== typeof getPath(node, path);\n }\n throw new Error(`Unknown selector value type: ${selector.value.type}`);\n case '<=':\n return (node) => getPath(node, path) <= selector.value.value;\n case '<':\n return (node) => getPath(node, path) < selector.value.value;\n case '>':\n return (node) => getPath(node, path) > selector.value.value;\n case '>=':\n return (node) => getPath(node, path) >= selector.value.value;\n }\n throw new Error(`Unknown operator: ${selector.operator}`);\n }\n\n case 'sibling': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n sibling(node, left, ancestry, LEFT_SIDE, options) ||\n selector.left.subject &&\n left(node, ancestry, options) &&\n sibling(node, right, ancestry, RIGHT_SIDE, options);\n }\n\n case 'adjacent': {\n const left = getMatcher(selector.left);\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n adjacent(node, left, ancestry, LEFT_SIDE, options) ||\n selector.right.subject &&\n left(node, ancestry, options) &&\n adjacent(node, right, ancestry, RIGHT_SIDE, options);\n }\n\n case 'nth-child': {\n const nth = selector.index.value;\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n nthChild(node, ancestry, nth, options);\n }\n\n case 'nth-last-child': {\n const nth = -selector.index.value;\n const right = getMatcher(selector.right);\n return (node, ancestry, options) =>\n right(node, ancestry, options) &&\n nthChild(node, ancestry, nth, options);\n }\n\n case 'class': {\n \n const name = selector.name.toLowerCase();\n\n return (node, ancestry, options) => {\n \n if (options && options.matchClass) {\n return options.matchClass(selector.name, node, ancestry);\n }\n \n if (options && options.nodeTypeKey) return false; \n\n switch(name){\n case 'statement':\n if(node.type.slice(-9) === 'Statement') return true;\n // fallthrough: interface Declaration <: Statement { }\n case 'declaration':\n return node.type.slice(-11) === 'Declaration';\n case 'pattern':\n if(node.type.slice(-7) === 'Pattern') return true;\n // fallthrough: interface Expression <: Node, Pattern { }\n case 'expression':\n return node.type.slice(-10) === 'Expression' ||\n node.type.slice(-7) === 'Literal' ||\n (\n node.type === 'Identifier' &&\n (ancestry.length === 0 || ancestry[0].type !== 'MetaProperty')\n ) ||\n node.type === 'MetaProperty';\n case 'function':\n return node.type === 'FunctionDeclaration' ||\n node.type === 'FunctionExpression' ||\n node.type === 'ArrowFunctionExpression';\n }\n throw new Error(`Unknown class name: ${selector.name}`);\n };\n }\n }\n\n throw new Error(`Unknown selector type: ${selector.type}`);\n}\n\n/**\n * @callback TraverseOptionFallback\n * @param {external:AST} node The given node.\n * @returns {string[]} An array of visitor keys for the given node.\n */\n\n/**\n * @callback ClassMatcher\n * @param {string} className The name of the class to match.\n * @param {external:AST} node The node to match against.\n * @param {Array} ancestry The ancestry of the node.\n * @returns {boolean} True if the node matches the class, false if not.\n */\n\n/**\n * @typedef {object} ESQueryOptions\n * @property {string} [nodeTypeKey=\"type\"] By passing `nodeTypeKey`, we can allow other ASTs to use ESQuery.\n * @property { { [nodeType: string]: string[] } } [visitorKeys] By passing `visitorKeys` mapping, we can extend the properties of the nodes that traverse the node.\n * @property {TraverseOptionFallback} [fallback] By passing `fallback` option, we can control the properties of traversing nodes when encountering unknown nodes.\n * @property {ClassMatcher} [matchClass] By passing `matchClass` option, we can customize the interpretation of classes.\n */\n\n/**\n * Given a `node` and its ancestors, determine if `node` is matched\n * by `selector`.\n * @param {?external:AST} node\n * @param {?SelectorAST} selector\n * @param {external:AST[]} [ancestry=[]]\n * @param {ESQueryOptions} [options]\n * @throws {Error} Unknowns (operator, class name, selector type, or\n * selector value type)\n * @returns {boolean}\n */\nfunction matches(node, selector, ancestry, options) {\n if (!selector) { return true; }\n if (!node) { return false; }\n if (!ancestry) { ancestry = []; }\n\n return getMatcher(selector)(node, ancestry, options);\n}\n\n/**\n * Get visitor keys of a given node.\n * @param {external:AST} node The AST node to get keys.\n * @param {ESQueryOptions|undefined} options\n * @returns {string[]} Visitor keys of the node.\n */\nfunction getVisitorKeys(node, options) {\n const nodeTypeKey = (options && options.nodeTypeKey) || 'type';\n\n const nodeType = node[nodeTypeKey];\n if (options && options.visitorKeys && options.visitorKeys[nodeType]) {\n return options.visitorKeys[nodeType];\n }\n if (estraverse.VisitorKeys[nodeType]) {\n return estraverse.VisitorKeys[nodeType];\n }\n if (options && typeof options.fallback === 'function') {\n return options.fallback(node);\n }\n // 'iteration' fallback\n return Object.keys(node).filter(function (key) {\n return key !== nodeTypeKey;\n });\n}\n\n\n/**\n * Check whether the given value is an ASTNode or not.\n * @param {any} node The value to check.\n * @param {ESQueryOptions|undefined} options The options to use.\n * @returns {boolean} `true` if the value is an ASTNode.\n */\nfunction isNode(node, options) {\n const nodeTypeKey = (options && options.nodeTypeKey) || 'type';\n return node !== null && typeof node === 'object' && typeof node[nodeTypeKey] === 'string';\n}\n\n/**\n * Determines if the given node has a sibling that matches the\n * given selector matcher.\n * @param {external:AST} node\n * @param {SelectorMatcher} matcher\n * @param {external:AST[]} ancestry\n * @param {Side} side\n * @param {ESQueryOptions|undefined} options\n * @returns {boolean}\n */\nfunction sibling(node, matcher, ancestry, side, options) {\n const [parent] = ancestry;\n if (!parent) { return false; }\n const keys = getVisitorKeys(parent, options);\n for (let i = 0; i < keys.length; ++i) {\n const listProp = parent[keys[i]];\n if (Array.isArray(listProp)) {\n const startIndex = listProp.indexOf(node);\n if (startIndex < 0) { continue; }\n let lowerBound, upperBound;\n if (side === LEFT_SIDE) {\n lowerBound = 0;\n upperBound = startIndex;\n } else {\n lowerBound = startIndex + 1;\n upperBound = listProp.length;\n }\n for (let k = lowerBound; k < upperBound; ++k) {\n if (isNode(listProp[k], options) && matcher(listProp[k], ancestry, options)) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\n/**\n * Determines if the given node has an adjacent sibling that matches\n * the given selector matcher.\n * @param {external:AST} node\n * @param {SelectorMatcher} matcher\n * @param {external:AST[]} ancestry\n * @param {Side} side\n * @param {ESQueryOptions|undefined} options\n * @returns {boolean}\n */\nfunction adjacent(node, matcher, ancestry, side, options) {\n const [parent] = ancestry;\n if (!parent) { return false; }\n const keys = getVisitorKeys(parent, options);\n for (let i = 0; i < keys.length; ++i) {\n const listProp = parent[keys[i]];\n if (Array.isArray(listProp)) {\n const idx = listProp.indexOf(node);\n if (idx < 0) { continue; }\n if (side === LEFT_SIDE && idx > 0 && isNode(listProp[idx - 1], options) && matcher(listProp[idx - 1], ancestry, options)) {\n return true;\n }\n if (side === RIGHT_SIDE && idx < listProp.length - 1 && isNode(listProp[idx + 1], options) && matcher(listProp[idx + 1], ancestry, options)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Determines if the given node is the `nth` child.\n * If `nth` is negative then the position is counted\n * from the end of the list of children.\n * @param {external:AST} node\n * @param {external:AST[]} ancestry\n * @param {Integer} nth\n * @param {ESQueryOptions|undefined} options\n * @returns {boolean}\n */\nfunction nthChild(node, ancestry, nth, options) {\n if (nth === 0) { return false; }\n const [parent] = ancestry;\n if (!parent) { return false; }\n const keys = getVisitorKeys(parent, options);\n for (let i = 0; i < keys.length; ++i) {\n const listProp = parent[keys[i]];\n if (Array.isArray(listProp)){\n const idx = nth < 0 ? listProp.length + nth : nth - 1;\n if (idx >= 0 && idx < listProp.length && listProp[idx] === node) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * For each selector node marked as a subject, find the portion of the\n * selector that the subject must match.\n * @param {SelectorAST} selector\n * @param {SelectorAST} [ancestor] Defaults to `selector`\n * @returns {SelectorAST[]}\n */\nfunction subjects(selector, ancestor) {\n if (selector == null || typeof selector != 'object') { return []; }\n if (ancestor == null) { ancestor = selector; }\n const results = selector.subject ? [ancestor] : [];\n const keys = Object.keys(selector);\n for (let i = 0; i < keys.length; ++i) {\n const p = keys[i];\n const sel = selector[p];\n results.push(...subjects(sel, p === 'left' ? sel : ancestor));\n }\n return results;\n}\n\n/**\n* @callback TraverseVisitor\n* @param {?external:AST} node\n* @param {?external:AST} parent\n* @param {external:AST[]} ancestry\n*/\n\n/**\n * From a JS AST and a selector AST, collect all JS AST nodes that\n * match the selector.\n * @param {external:AST} ast\n * @param {?SelectorAST} selector\n * @param {TraverseVisitor} visitor\n * @param {ESQueryOptions} [options]\n * @returns {external:AST[]}\n */\nfunction traverse(ast, selector, visitor, options) {\n if (!selector) { return; }\n const ancestry = [];\n const matcher = getMatcher(selector);\n const altSubjects = subjects(selector).map(getMatcher);\n estraverse.traverse(ast, {\n enter (node, parent) {\n if (parent != null) { ancestry.unshift(parent); }\n if (matcher(node, ancestry, options)) {\n if (altSubjects.length) {\n for (let i = 0, l = altSubjects.length; i < l; ++i) {\n if (altSubjects[i](node, ancestry, options)) {\n visitor(node, parent, ancestry);\n }\n for (let k = 0, m = ancestry.length; k < m; ++k) {\n const succeedingAncestry = ancestry.slice(k + 1);\n if (altSubjects[i](ancestry[k], succeedingAncestry, options)) {\n visitor(ancestry[k], parent, succeedingAncestry);\n }\n }\n }\n } else {\n visitor(node, parent, ancestry);\n }\n }\n },\n leave () { ancestry.shift(); },\n keys: options && options.visitorKeys,\n fallback: options && options.fallback || 'iteration'\n });\n}\n\n\n/**\n * From a JS AST and a selector AST, collect all JS AST nodes that\n * match the selector.\n * @param {external:AST} ast\n * @param {?SelectorAST} selector\n * @param {ESQueryOptions} [options]\n * @returns {external:AST[]}\n */\nfunction match(ast, selector, options) {\n const results = [];\n traverse(ast, selector, function (node) {\n results.push(node);\n }, options);\n return results;\n}\n\n/**\n * Parse a selector string and return its AST.\n * @param {string} selector\n * @returns {SelectorAST}\n */\nfunction parse(selector) {\n return parser.parse(selector);\n}\n\n/**\n * Query the code AST using the selector string.\n * @param {external:AST} ast\n * @param {string} selector\n * @param {ESQueryOptions} [options]\n * @returns {external:AST[]}\n */\nfunction query(ast, selector, options) {\n return match(ast, parse(selector), options);\n}\n\nquery.parse = parse;\nquery.match = match;\nquery.traverse = traverse;\nquery.matches = matches;\nquery.query = query;\n\nexport default query;\n"],"names":["clone","exports","Syntax","VisitorOption","VisitorKeys","BREAK","SKIP","REMOVE","deepCopy","obj","key","val","ret","hasOwnProperty","Reference","parent","this","Element","node","path","wrap","ref","Controller","isNode","type","isProperty","nodeType","ObjectExpression","ObjectPattern","candidateExistsInLeaveList","leavelist","candidate","i","length","traverse","root","visitor","extendCommentRange","comment","tokens","target","array","func","diff","len","current","upperBound","token","range","extendedRange","AssignmentExpression","AssignmentPattern","ArrayExpression","ArrayPattern","ArrowFunctionExpression","AwaitExpression","BlockStatement","BinaryExpression","BreakStatement","CallExpression","CatchClause","ChainExpression","ClassBody","ClassDeclaration","ClassExpression","ComprehensionBlock","ComprehensionExpression","ConditionalExpression","ContinueStatement","DebuggerStatement","DirectiveStatement","DoWhileStatement","EmptyStatement","ExportAllDeclaration","ExportDefaultDeclaration","ExportNamedDeclaration","ExportSpecifier","ExpressionStatement","ForStatement","ForInStatement","ForOfStatement","FunctionDeclaration","FunctionExpression","GeneratorExpression","Identifier","IfStatement","ImportExpression","ImportDeclaration","ImportDefaultSpecifier","ImportNamespaceSpecifier","ImportSpecifier","Literal","LabeledStatement","LogicalExpression","MemberExpression","MetaProperty","MethodDefinition","ModuleSpecifier","NewExpression","PrivateIdentifier","Program","Property","PropertyDefinition","RestElement","ReturnStatement","SequenceExpression","SpreadElement","Super","SwitchStatement","SwitchCase","TaggedTemplateExpression","TemplateElement","TemplateLiteral","ThisExpression","ThrowStatement","TryStatement","UnaryExpression","UpdateExpression","VariableDeclaration","VariableDeclarator","WhileStatement","WithStatement","YieldExpression","Break","Skip","Remove","prototype","replace","remove","Array","isArray","splice","iz","j","jz","result","addToPath","push","__current","__leavelist","parents","__execute","callback","element","previous","undefined","__state","call","notify","flag","skip","__initialize","__worklist","__fallback","fallback","Object","keys","__keys","assign","create","worklist","current2","candidates","sentinel","pop","enter","Error","leave","outer","removeElem","nextElem","attachComments","tree","providedComments","cursor","comments","leadingComments","trailingComments","cloneEnvironment","module","peg$SyntaxError","message","expected","found","location","name","captureStackTrace","child","ctor","constructor","peg$subclass","buildMessage","DESCRIBE_EXPECTATION_FNS","literal","expectation","literalEscape","text","class","escapedParts","parts","classEscape","inverted","any","end","other","description","hex","ch","charCodeAt","toString","toUpperCase","s","descriptions","sort","slice","join","describeExpected","describeFound","SyntaxError","parse","input","options","peg$result","peg$FAILED","peg$startRuleFunctions","start","peg$parsestart","peg$startRuleFunction","peg$c3","peg$literalExpectation","peg$c4","peg$c5","peg$classExpectation","peg$c8","peg$c11","peg$c14","peg$c18","peg$c19","ss","concat","map","peg$c23","peg$c26","peg$c29","peg$c32","peg$c34","peg$c36","peg$c37","peg$c39","peg$c40","a","peg$c41","peg$c42","peg$c44","peg$c46","op","value","operator","peg$c49","peg$c50","peg$c51","peg$c53","peg$c54","peg$c55","b","peg$c56","d","match","peg$c58","peg$c59","peg$c60","peg$c61","peg$c62","peg$c66","peg$c67","peg$c68","peg$c70","peg$c72","peg$c73","peg$c75","peg$c77","peg$c78","peg$c81","peg$c82","peg$c86","peg$c89","peg$c90","selectors","peg$c92","peg$c94","peg$c97","peg$c100","peg$c103","peg$c106","peg$c109","peg$currPos","peg$posDetailsCache","line","column","peg$maxFailPos","peg$maxFailExpected","peg$silentFails","startRule","ignoreCase","peg$computePosDetails","pos","p","details","peg$computeLocation","startPos","endPos","startPosDetails","endPosDetails","offset","peg$fail","s0","s1","s2","cached","peg$resultsCache","nextPos","peg$parse_","peg$parseselectors","peg$c1","peg$parseidentifierName","test","charAt","peg$parsebinaryOp","s3","s4","s5","s6","s7","peg$parseselector","peg$parsehasSelector","left","right","peg$parsesequence","reduce","memo","rhs","subject","as","peg$parseatom","peg$parsewildcard","peg$parseidentifier","peg$parseattrName","peg$parseattrEqOps","substr","peg$parsetype","flgs","peg$parsere_character_class","peg$parsere_escape","peg$parsere_chars","peg$parseflags","RegExp","peg$parseregex","peg$parseattrOps","peg$parsestring","leadingDecimals","apply","parseFloat","peg$parsenumber","peg$parsepath","peg$parseattrValue","peg$parseattr","peg$parsefield","peg$parsenegation","peg$parsematches","peg$parseis","peg$parsehasSelectors","peg$parsehas","nth","peg$parsefirstChild","nthLast","peg$parselastChild","parseInt","peg$parsenthChild","peg$parsenthLastChild","peg$parseclass","n","index","factory","getPath","MATCHER_CACHE","WeakMap","getMatcher","selector","matcher","get","generateMatcher","set","toLowerCase","ancestry","nodeTypeKey","split","inPath","ancestor","fromPathIndex","field","k","matchers","estraverse","unshift","shift","visitorKeys","l","_typeof","sibling","adjacent","nthChild","matchClass","getVisitorKeys","filter","side","_slicedToArray","listProp","startIndex","indexOf","lowerBound","idx","ast","altSubjects","subjects","results","sel","_toConsumableArray","m","succeedingAncestry","parser","query","matches"],"mappings":"m/DA2BC,SAASA,EAAMC,GAGZ,IAAIC,EACAC,EACAC,EACAC,EACAC,EACAC,EAEJ,SAASC,EAASC,GACd,IAAcC,EAAKC,EAAfC,EAAM,GACV,IAAKF,KAAOD,E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mE,GAAWA,EAAQnE,UAAY,eAajD,SAASiH,EAAM0J,EAAKlC,EAAUtK,GAC1B,IAAM2M,EAAU,GAIhB,OAHAtY,EAASmY,EAAKlC,GAAU,SAAUjX,GAC9BsZ,EAAQ/R,KAAKvH,KACd2M,GACI2M,EAQX,SAAS7M,EAAMwK,GACX,OAAO0C,EAAOlN,MAAMwK,GAUxB,SAAS2C,EAAMT,EAAKlC,EAAUtK,GAC1B,OAAO8C,EAAM0J,EAAK1M,EAAMwK,GAAWtK,UAGvCiN,EAAMnN,MAAQA,EACdmN,EAAMnK,MAAQA,EACdmK,EAAM5Y,SAAWA,EACjB4Y,EAAMC,QAvPN,SAAiB7Z,EAAMiX,EAAUM,EAAU5K,GACvC,OAAKsK,KACAjX,IACAuX,IAAYA,EAAW,IAErBP,EAAWC,EAAXD,CAAqBhX,EAAMuX,EAAU5K,KAmPhDiN,EAAMA,MAAQA"} \ No newline at end of file diff --git a/node_modules/esquery/license.txt b/node_modules/esquery/license.txt new file mode 100644 index 0000000000000000000000000000000000000000..52f915e2688a40f34e1fa073aec37e43b9c5c1d6 --- /dev/null +++ b/node_modules/esquery/license.txt @@ -0,0 +1,24 @@ +Copyright (c) 2013, Joel Feenstra +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 the ESQuery 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 JOEL FEENSTRA 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. diff --git a/node_modules/esquery/package.json b/node_modules/esquery/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b494042b776ec036dcc0ee99581273d72d0580d7 --- /dev/null +++ b/node_modules/esquery/package.json @@ -0,0 +1,78 @@ +{ + "name": "esquery", + "version": "1.7.0", + "author": "Joel Feenstra ", + "contributors": [], + "description": "A query library for ECMAScript AST using a CSS selector like query language.", + "main": "dist/esquery.min.js", + "module": "dist/esquery.esm.min.js", + "files": [ + "dist/*.js", + "dist/*.map", + "parser.js", + "license.txt", + "README.md" + ], + "nyc": { + "branches": 100, + "lines": 100, + "functions": 100, + "statements": 100, + "reporter": [ + "html", + "text" + ], + "exclude": [ + "parser.js", + "dist", + "tests" + ] + }, + "scripts": { + "prepublishOnly": "npm run build && npm test", + "build:parser": "rm parser.js && pegjs --cache --format umd -o \"parser.js\" \"grammar.pegjs\"", + "build:browser": "rollup -c", + "build": "npm run build:parser && npm run build:browser", + "mocha": "mocha --require chai/register-assert --require @babel/register tests", + "test": "nyc npm run mocha && npm run lint", + "test:ci": "npm run mocha", + "lint": "eslint ." + }, + "repository": { + "type": "git", + "url": "https://github.com/estools/esquery.git" + }, + "bugs": "https://github.com/estools/esquery/issues", + "homepage": "https://github.com/estools/esquery/", + "keywords": [ + "ast", + "ecmascript", + "javascript", + "query" + ], + "devDependencies": { + "@babel/core": "^7.9.0", + "@babel/preset-env": "^7.9.5", + "@babel/register": "^7.9.0", + "@rollup/plugin-commonjs": "^11.1.0", + "@rollup/plugin-json": "^4.0.2", + "@rollup/plugin-node-resolve": "^7.1.3", + "babel-plugin-transform-es2017-object-entries": "0.0.5", + "chai": "4.2.0", + "eslint": "^6.8.0", + "esprima": "~4.0.1", + "mocha": "7.1.1", + "nyc": "^15.0.1", + "pegjs": "~0.10.0", + "rollup": "^1.32.1", + "rollup-plugin-babel": "^4.4.0", + "rollup-plugin-terser": "^5.3.0" + }, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10" + }, + "dependencies": { + "estraverse": "^5.1.0" + } +} diff --git a/node_modules/esquery/parser.js b/node_modules/esquery/parser.js new file mode 100644 index 0000000000000000000000000000000000000000..c6fd7419e6959566fbeb2967a7c1b6ee69e4a730 --- /dev/null +++ b/node_modules/esquery/parser.js @@ -0,0 +1,2941 @@ +/* + * Generated by PEG.js 0.10.0. + * + * http://pegjs.org/ + */ +(function(root, factory) { + if (typeof define === "function" && define.amd) { + define([], factory); + } else if (typeof module === "object" && module.exports) { + module.exports = factory(); + } +})(this, function() { + "use strict"; + + function peg$subclass(child, parent) { + function ctor() { this.constructor = child; } + ctor.prototype = parent.prototype; + child.prototype = new ctor(); + } + + function peg$SyntaxError(message, expected, found, location) { + this.message = message; + this.expected = expected; + this.found = found; + this.location = location; + this.name = "SyntaxError"; + + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, peg$SyntaxError); + } + } + + peg$subclass(peg$SyntaxError, Error); + + peg$SyntaxError.buildMessage = function(expected, found) { + var DESCRIBE_EXPECTATION_FNS = { + literal: function(expectation) { + return "\"" + literalEscape(expectation.text) + "\""; + }, + + "class": function(expectation) { + var escapedParts = "", + i; + + for (i = 0; i < expectation.parts.length; i++) { + escapedParts += expectation.parts[i] instanceof Array + ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) + : classEscape(expectation.parts[i]); + } + + return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; + }, + + any: function(expectation) { + return "any character"; + }, + + end: function(expectation) { + return "end of input"; + }, + + other: function(expectation) { + return expectation.description; + } + }; + + function hex(ch) { + return ch.charCodeAt(0).toString(16).toUpperCase(); + } + + function literalEscape(s) { + return s + .replace(/\\/g, '\\\\') + .replace(/"/g, '\\"') + .replace(/\0/g, '\\0') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); + } + + function classEscape(s) { + return s + .replace(/\\/g, '\\\\') + .replace(/\]/g, '\\]') + .replace(/\^/g, '\\^') + .replace(/-/g, '\\-') + .replace(/\0/g, '\\0') + .replace(/\t/g, '\\t') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); + } + + function describeExpectation(expectation) { + return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); + } + + function describeExpected(expected) { + var descriptions = new Array(expected.length), + i, j; + + for (i = 0; i < expected.length; i++) { + descriptions[i] = describeExpectation(expected[i]); + } + + descriptions.sort(); + + if (descriptions.length > 0) { + for (i = 1, j = 1; i < descriptions.length; i++) { + if (descriptions[i - 1] !== descriptions[i]) { + descriptions[j] = descriptions[i]; + j++; + } + } + descriptions.length = j; + } + + switch (descriptions.length) { + case 1: + return descriptions[0]; + + case 2: + return descriptions[0] + " or " + descriptions[1]; + + default: + return descriptions.slice(0, -1).join(", ") + + ", or " + + descriptions[descriptions.length - 1]; + } + } + + function describeFound(found) { + return found ? "\"" + literalEscape(found) + "\"" : "end of input"; + } + + return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; + }; + + function peg$parse(input, options) { + options = options !== void 0 ? options : {}; + + var peg$FAILED = {}, + + peg$startRuleFunctions = { start: peg$parsestart }, + peg$startRuleFunction = peg$parsestart, + + peg$c0 = function(ss) { + return ss.length === 1 ? ss[0] : { type: 'matches', selectors: ss }; + }, + peg$c1 = function() { return void 0; }, + peg$c2 = " ", + peg$c3 = peg$literalExpectation(" ", false), + peg$c4 = /^[^ [\],():#!=><~+.]/, + peg$c5 = peg$classExpectation([" ", "[", "]", ",", "(", ")", ":", "#", "!", "=", ">", "<", "~", "+", "."], true, false), + peg$c6 = function(i) { return i.join(''); }, + peg$c7 = ">", + peg$c8 = peg$literalExpectation(">", false), + peg$c9 = function() { return 'child'; }, + peg$c10 = "~", + peg$c11 = peg$literalExpectation("~", false), + peg$c12 = function() { return 'sibling'; }, + peg$c13 = "+", + peg$c14 = peg$literalExpectation("+", false), + peg$c15 = function() { return 'adjacent'; }, + peg$c16 = function() { return 'descendant'; }, + peg$c17 = ",", + peg$c18 = peg$literalExpectation(",", false), + peg$c19 = function(s, ss) { + return [s].concat(ss.map(function (s) { return s[3]; })); + }, + peg$c20 = function(op, s) { + if (!op) return s; + return { type: op, left: { type: 'exactNode' }, right: s }; + }, + peg$c21 = function(a, ops) { + return ops.reduce(function (memo, rhs) { + return { type: rhs[0], left: memo, right: rhs[1] }; + }, a); + }, + peg$c22 = "!", + peg$c23 = peg$literalExpectation("!", false), + peg$c24 = function(subject, as) { + const b = as.length === 1 ? as[0] : { type: 'compound', selectors: as }; + if(subject) b.subject = true; + return b; + }, + peg$c25 = "*", + peg$c26 = peg$literalExpectation("*", false), + peg$c27 = function(a) { return { type: 'wildcard', value: a }; }, + peg$c28 = "#", + peg$c29 = peg$literalExpectation("#", false), + peg$c30 = function(i) { return { type: 'identifier', value: i }; }, + peg$c31 = "[", + peg$c32 = peg$literalExpectation("[", false), + peg$c33 = "]", + peg$c34 = peg$literalExpectation("]", false), + peg$c35 = function(v) { return v; }, + peg$c36 = /^[>", "<", "!"], false, false), + peg$c38 = "=", + peg$c39 = peg$literalExpectation("=", false), + peg$c40 = function(a) { return (a || '') + '='; }, + peg$c41 = /^[><]/, + peg$c42 = peg$classExpectation([">", "<"], false, false), + peg$c43 = ".", + peg$c44 = peg$literalExpectation(".", false), + peg$c45 = function(a, as) { + return [].concat.apply([a], as).join(''); + }, + peg$c46 = function(name, op, value) { + return { type: 'attribute', name: name, operator: op, value: value }; + }, + peg$c47 = function(name) { return { type: 'attribute', name: name }; }, + peg$c48 = "\"", + peg$c49 = peg$literalExpectation("\"", false), + peg$c50 = /^[^\\"]/, + peg$c51 = peg$classExpectation(["\\", "\""], true, false), + peg$c52 = "\\", + peg$c53 = peg$literalExpectation("\\", false), + peg$c54 = peg$anyExpectation(), + peg$c55 = function(a, b) { return a + b; }, + peg$c56 = function(d) { + return { type: 'literal', value: strUnescape(d.join('')) }; + }, + peg$c57 = "'", + peg$c58 = peg$literalExpectation("'", false), + peg$c59 = /^[^\\']/, + peg$c60 = peg$classExpectation(["\\", "'"], true, false), + peg$c61 = /^[0-9]/, + peg$c62 = peg$classExpectation([["0", "9"]], false, false), + peg$c63 = function(a, b) { + // Can use `a.flat().join('')` once supported + const leadingDecimals = a ? [].concat.apply([], a).join('') : ''; + return { type: 'literal', value: parseFloat(leadingDecimals + b.join('')) }; + }, + peg$c64 = function(i) { return { type: 'literal', value: i }; }, + peg$c65 = "type(", + peg$c66 = peg$literalExpectation("type(", false), + peg$c67 = /^[^ )]/, + peg$c68 = peg$classExpectation([" ", ")"], true, false), + peg$c69 = ")", + peg$c70 = peg$literalExpectation(")", false), + peg$c71 = function(t) { return { type: 'type', value: t.join('') }; }, + peg$c72 = /^[imsu]/, + peg$c73 = peg$classExpectation(["i", "m", "s", "u"], false, false), + peg$c74 = "/", + peg$c75 = peg$literalExpectation("/", false), + peg$c76 = function(pattern, flgs) { + return { + type: 'regexp', value: new RegExp(pattern.join(''), flgs ? flgs.join('') : '') + }; + }, + peg$c77 = /^[^\]\\]/, + peg$c78 = peg$classExpectation(["]", "\\"], true, false), + peg$c79 = function(cs) { return '[' + cs.join('') + ']'; }, + peg$c80 = function(a) { return '\\' + a; }, + peg$c81 = /^[^\/\\[]/, + peg$c82 = peg$classExpectation(["/", "\\", "["], true, false), + peg$c83 = function(cs) { return cs.join(''); }, + peg$c84 = function(i, is) { + return { type: 'field', name: is.reduce(function(memo, p){ return memo + p[0] + p[1]; }, i)}; + }, + peg$c85 = ":not(", + peg$c86 = peg$literalExpectation(":not(", false), + peg$c87 = function(ss) { return { type: 'not', selectors: ss }; }, + peg$c88 = ":matches(", + peg$c89 = peg$literalExpectation(":matches(", false), + peg$c90 = function(ss) { return { type: 'matches', selectors: ss }; }, + peg$c91 = ":is(", + peg$c92 = peg$literalExpectation(":is(", false), + peg$c93 = ":has(", + peg$c94 = peg$literalExpectation(":has(", false), + peg$c95 = function(ss) { return { type: 'has', selectors: ss }; }, + peg$c96 = ":first-child", + peg$c97 = peg$literalExpectation(":first-child", false), + peg$c98 = function() { return nth(1); }, + peg$c99 = ":last-child", + peg$c100 = peg$literalExpectation(":last-child", false), + peg$c101 = function() { return nthLast(1); }, + peg$c102 = ":nth-child(", + peg$c103 = peg$literalExpectation(":nth-child(", false), + peg$c104 = function(n) { return nth(parseInt(n.join(''), 10)); }, + peg$c105 = ":nth-last-child(", + peg$c106 = peg$literalExpectation(":nth-last-child(", false), + peg$c107 = function(n) { return nthLast(parseInt(n.join(''), 10)); }, + peg$c108 = ":", + peg$c109 = peg$literalExpectation(":", false), + peg$c110 = function(c) { + return { type: 'class', name: c }; + }, + + peg$currPos = 0, + peg$savedPos = 0, + peg$posDetailsCache = [{ line: 1, column: 1 }], + peg$maxFailPos = 0, + peg$maxFailExpected = [], + peg$silentFails = 0, + + peg$resultsCache = {}, + + peg$result; + + if ("startRule" in options) { + if (!(options.startRule in peg$startRuleFunctions)) { + throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); + } + + peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; + } + + function text() { + return input.substring(peg$savedPos, peg$currPos); + } + + function location() { + return peg$computeLocation(peg$savedPos, peg$currPos); + } + + function expected(description, location) { + location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos) + + throw peg$buildStructuredError( + [peg$otherExpectation(description)], + input.substring(peg$savedPos, peg$currPos), + location + ); + } + + function error(message, location) { + location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos) + + throw peg$buildSimpleError(message, location); + } + + function peg$literalExpectation(text, ignoreCase) { + return { type: "literal", text: text, ignoreCase: ignoreCase }; + } + + function peg$classExpectation(parts, inverted, ignoreCase) { + return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase }; + } + + function peg$anyExpectation() { + return { type: "any" }; + } + + function peg$endExpectation() { + return { type: "end" }; + } + + function peg$otherExpectation(description) { + return { type: "other", description: description }; + } + + function peg$computePosDetails(pos) { + var details = peg$posDetailsCache[pos], p; + + if (details) { + return details; + } else { + p = pos - 1; + while (!peg$posDetailsCache[p]) { + p--; + } + + details = peg$posDetailsCache[p]; + details = { + line: details.line, + column: details.column + }; + + while (p < pos) { + if (input.charCodeAt(p) === 10) { + details.line++; + details.column = 1; + } else { + details.column++; + } + + p++; + } + + peg$posDetailsCache[pos] = details; + return details; + } + } + + function peg$computeLocation(startPos, endPos) { + var startPosDetails = peg$computePosDetails(startPos), + endPosDetails = peg$computePosDetails(endPos); + + return { + start: { + offset: startPos, + line: startPosDetails.line, + column: startPosDetails.column + }, + end: { + offset: endPos, + line: endPosDetails.line, + column: endPosDetails.column + } + }; + } + + function peg$fail(expected) { + if (peg$currPos < peg$maxFailPos) { return; } + + if (peg$currPos > peg$maxFailPos) { + peg$maxFailPos = peg$currPos; + peg$maxFailExpected = []; + } + + peg$maxFailExpected.push(expected); + } + + function peg$buildSimpleError(message, location) { + return new peg$SyntaxError(message, null, null, location); + } + + function peg$buildStructuredError(expected, found, location) { + return new peg$SyntaxError( + peg$SyntaxError.buildMessage(expected, found), + expected, + found, + location + ); + } + + function peg$parsestart() { + var s0, s1, s2, s3; + + var key = peg$currPos * 36 + 0, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + s2 = peg$parseselectors(); + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c0(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c1(); + } + s0 = s1; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parse_() { + var s0, s1; + + var key = peg$currPos * 36 + 1, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = []; + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c3); } + } + while (s1 !== peg$FAILED) { + s0.push(s1); + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c3); } + } + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseidentifierName() { + var s0, s1, s2; + + var key = peg$currPos * 36 + 2, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + if (peg$c4.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c5); } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + if (peg$c4.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c5); } + } + } + } else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c6(s1); + } + s0 = s1; + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsebinaryOp() { + var s0, s1, s2, s3; + + var key = peg$currPos * 36 + 3, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 62) { + s2 = peg$c7; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c8); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c9(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 126) { + s2 = peg$c10; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c11); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c12(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parse_(); + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 43) { + s2 = peg$c13; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c14); } + } + if (s2 !== peg$FAILED) { + s3 = peg$parse_(); + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c15(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 32) { + s1 = peg$c2; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c3); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c16(); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + } + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsehasSelectors() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + var key = peg$currPos * 36 + 4, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsehasSelector(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c18); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parsehasSelector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c18); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parsehasSelector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseselectors() { + var s0, s1, s2, s3, s4, s5, s6, s7; + + var key = peg$currPos * 36 + 5, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parseselector(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c18); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseselector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 44) { + s5 = peg$c17; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c18); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parse_(); + if (s6 !== peg$FAILED) { + s7 = peg$parseselector(); + if (s7 !== peg$FAILED) { + s4 = [s4, s5, s6, s7]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c19(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsehasSelector() { + var s0, s1, s2; + + var key = peg$currPos * 36 + 6, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsebinaryOp(); + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseselector(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c20(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseselector() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 7, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parsesequence(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + s4 = peg$parsebinaryOp(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesequence(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + s4 = peg$parsebinaryOp(); + if (s4 !== peg$FAILED) { + s5 = peg$parsesequence(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c21(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsesequence() { + var s0, s1, s2, s3; + + var key = peg$currPos * 36 + 8, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 33) { + s1 = peg$c22; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c23); } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parseatom(); + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parseatom(); + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c24(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseatom() { + var s0; + + var key = peg$currPos * 36 + 9, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$parsewildcard(); + if (s0 === peg$FAILED) { + s0 = peg$parseidentifier(); + if (s0 === peg$FAILED) { + s0 = peg$parseattr(); + if (s0 === peg$FAILED) { + s0 = peg$parsefield(); + if (s0 === peg$FAILED) { + s0 = peg$parsenegation(); + if (s0 === peg$FAILED) { + s0 = peg$parsematches(); + if (s0 === peg$FAILED) { + s0 = peg$parseis(); + if (s0 === peg$FAILED) { + s0 = peg$parsehas(); + if (s0 === peg$FAILED) { + s0 = peg$parsefirstChild(); + if (s0 === peg$FAILED) { + s0 = peg$parselastChild(); + if (s0 === peg$FAILED) { + s0 = peg$parsenthChild(); + if (s0 === peg$FAILED) { + s0 = peg$parsenthLastChild(); + if (s0 === peg$FAILED) { + s0 = peg$parseclass(); + } + } + } + } + } + } + } + } + } + } + } + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsewildcard() { + var s0, s1; + + var key = peg$currPos * 36 + 10, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 42) { + s1 = peg$c25; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c26); } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c27(s1); + } + s0 = s1; + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseidentifier() { + var s0, s1, s2; + + var key = peg$currPos * 36 + 11, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 35) { + s1 = peg$c28; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c29); } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c30(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseattr() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 12, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c31; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrValue(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s5 = peg$c33; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c34); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c35(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseattrOps() { + var s0, s1, s2; + + var key = peg$currPos * 36 + 13, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (peg$c36.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c37); } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c39); } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c40(s1); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + if (peg$c41.test(input.charAt(peg$currPos))) { + s0 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s0 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c42); } + } + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseattrEqOps() { + var s0, s1, s2; + + var key = peg$currPos * 36 + 14, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 33) { + s1 = peg$c22; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c23); } + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 61) { + s2 = peg$c38; + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c39); } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c40(s1); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseattrName() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 15, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parseidentifierName(); + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c43; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c44); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseidentifierName(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s4 = peg$c43; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c44); } + } + if (s4 !== peg$FAILED) { + s5 = peg$parseidentifierName(); + if (s5 !== peg$FAILED) { + s4 = [s4, s5]; + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c45(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseattrValue() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 16, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrEqOps(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + s5 = peg$parsetype(); + if (s5 === peg$FAILED) { + s5 = peg$parseregex(); + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c46(s1, s3, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseattrOps(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + s5 = peg$parsestring(); + if (s5 === peg$FAILED) { + s5 = peg$parsenumber(); + if (s5 === peg$FAILED) { + s5 = peg$parsepath(); + } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c46(s1, s3, s5); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + s1 = peg$parseattrName(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c47(s1); + } + s0 = s1; + } + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsestring() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 17, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 34) { + s1 = peg$c48; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c49); } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c50.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c51); } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c53); } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c54); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s3; + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c50.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c51); } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c53); } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c54); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s3; + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 34) { + s3 = peg$c48; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c49); } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c56(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + if (s0 === peg$FAILED) { + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 39) { + s1 = peg$c57; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c58); } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c59.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c60); } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c53); } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c54); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s3; + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c59.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c60); } + } + if (s3 === peg$FAILED) { + s3 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s4 = peg$c52; + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c53); } + } + if (s4 !== peg$FAILED) { + if (input.length > peg$currPos) { + s5 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c54); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s3; + s4 = peg$c55(s4, s5); + s3 = s4; + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } else { + peg$currPos = s3; + s3 = peg$FAILED; + } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 39) { + s3 = peg$c57; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c58); } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c56(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsenumber() { + var s0, s1, s2, s3; + + var key = peg$currPos * 36 + 18, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$currPos; + s2 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 46) { + s3 = peg$c43; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c44); } + } + if (s3 !== peg$FAILED) { + s2 = [s2, s3]; + s1 = s2; + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + } else { + peg$currPos = s1; + s1 = peg$FAILED; + } + if (s1 === peg$FAILED) { + s1 = null; + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c61.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c63(s1, s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsepath() { + var s0, s1; + + var key = peg$currPos * 36 + 19, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = peg$parseidentifierName(); + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c64(s1); + } + s0 = s1; + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsetype() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 20, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c65) { + s1 = peg$c65; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c66); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c67.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c68); } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c67.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c68); } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c70); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c71(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseflags() { + var s0, s1; + + var key = peg$currPos * 36 + 21, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = []; + if (peg$c72.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + if (s1 !== peg$FAILED) { + while (s1 !== peg$FAILED) { + s0.push(s1); + if (peg$c72.test(input.charAt(peg$currPos))) { + s1 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c73); } + } + } + } else { + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseregex() { + var s0, s1, s2, s3, s4; + + var key = peg$currPos * 36 + 22, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 47) { + s1 = peg$c74; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c75); } + } + if (s1 !== peg$FAILED) { + s2 = []; + s3 = peg$parsere_character_class(); + if (s3 === peg$FAILED) { + s3 = peg$parsere_escape(); + if (s3 === peg$FAILED) { + s3 = peg$parsere_chars(); + } + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + s3 = peg$parsere_character_class(); + if (s3 === peg$FAILED) { + s3 = peg$parsere_escape(); + if (s3 === peg$FAILED) { + s3 = peg$parsere_chars(); + } + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 47) { + s3 = peg$c74; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c75); } + } + if (s3 !== peg$FAILED) { + s4 = peg$parseflags(); + if (s4 === peg$FAILED) { + s4 = null; + } + if (s4 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c76(s2, s4); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsere_character_class() { + var s0, s1, s2, s3; + + var key = peg$currPos * 36 + 23, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 91) { + s1 = peg$c31; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c32); } + } + if (s1 !== peg$FAILED) { + s2 = []; + if (peg$c77.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c78); } + } + if (s3 === peg$FAILED) { + s3 = peg$parsere_escape(); + } + if (s3 !== peg$FAILED) { + while (s3 !== peg$FAILED) { + s2.push(s3); + if (peg$c77.test(input.charAt(peg$currPos))) { + s3 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c78); } + } + if (s3 === peg$FAILED) { + s3 = peg$parsere_escape(); + } + } + } else { + s2 = peg$FAILED; + } + if (s2 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 93) { + s3 = peg$c33; + peg$currPos++; + } else { + s3 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c34); } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c79(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsere_escape() { + var s0, s1, s2; + + var key = peg$currPos * 36 + 24, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 92) { + s1 = peg$c52; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c53); } + } + if (s1 !== peg$FAILED) { + if (input.length > peg$currPos) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c54); } + } + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c80(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsere_chars() { + var s0, s1, s2; + + var key = peg$currPos * 36 + 25, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + s1 = []; + if (peg$c81.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c82); } + } + if (s2 !== peg$FAILED) { + while (s2 !== peg$FAILED) { + s1.push(s2); + if (peg$c81.test(input.charAt(peg$currPos))) { + s2 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s2 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c82); } + } + } + } else { + s1 = peg$FAILED; + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c83(s1); + } + s0 = s1; + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsefield() { + var s0, s1, s2, s3, s4, s5, s6; + + var key = peg$currPos * 36 + 26, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s1 = peg$c43; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c44); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + s3 = []; + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c43; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c44); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseidentifierName(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + while (s4 !== peg$FAILED) { + s3.push(s4); + s4 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 46) { + s5 = peg$c43; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c44); } + } + if (s5 !== peg$FAILED) { + s6 = peg$parseidentifierName(); + if (s6 !== peg$FAILED) { + s5 = [s5, s6]; + s4 = s5; + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } else { + peg$currPos = s4; + s4 = peg$FAILED; + } + } + if (s3 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c84(s2, s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsenegation() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 27, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c85) { + s1 = peg$c85; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c86); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c70); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c87(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsematches() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 28, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 9) === peg$c88) { + s1 = peg$c88; + peg$currPos += 9; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c89); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c70); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c90(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseis() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 29, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 4) === peg$c91) { + s1 = peg$c91; + peg$currPos += 4; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c92); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parseselectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c70); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c90(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsehas() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 30, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 5) === peg$c93) { + s1 = peg$c93; + peg$currPos += 5; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c94); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = peg$parsehasSelectors(); + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c70); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c95(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsefirstChild() { + var s0, s1; + + var key = peg$currPos * 36 + 31, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 12) === peg$c96) { + s1 = peg$c96; + peg$currPos += 12; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c97); } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c98(); + } + s0 = s1; + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parselastChild() { + var s0, s1; + + var key = peg$currPos * 36 + 32, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c99) { + s1 = peg$c99; + peg$currPos += 11; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c100); } + } + if (s1 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c101(); + } + s0 = s1; + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsenthChild() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 33, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 11) === peg$c102) { + s1 = peg$c102; + peg$currPos += 11; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c103); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c70); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c104(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parsenthLastChild() { + var s0, s1, s2, s3, s4, s5; + + var key = peg$currPos * 36 + 34, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.substr(peg$currPos, 16) === peg$c105) { + s1 = peg$c105; + peg$currPos += 16; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c106); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parse_(); + if (s2 !== peg$FAILED) { + s3 = []; + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + if (s4 !== peg$FAILED) { + while (s4 !== peg$FAILED) { + s3.push(s4); + if (peg$c61.test(input.charAt(peg$currPos))) { + s4 = input.charAt(peg$currPos); + peg$currPos++; + } else { + s4 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c62); } + } + } + } else { + s3 = peg$FAILED; + } + if (s3 !== peg$FAILED) { + s4 = peg$parse_(); + if (s4 !== peg$FAILED) { + if (input.charCodeAt(peg$currPos) === 41) { + s5 = peg$c69; + peg$currPos++; + } else { + s5 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c70); } + } + if (s5 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c107(s3); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + function peg$parseclass() { + var s0, s1, s2; + + var key = peg$currPos * 36 + 35, + cached = peg$resultsCache[key]; + + if (cached) { + peg$currPos = cached.nextPos; + + return cached.result; + } + + s0 = peg$currPos; + if (input.charCodeAt(peg$currPos) === 58) { + s1 = peg$c108; + peg$currPos++; + } else { + s1 = peg$FAILED; + if (peg$silentFails === 0) { peg$fail(peg$c109); } + } + if (s1 !== peg$FAILED) { + s2 = peg$parseidentifierName(); + if (s2 !== peg$FAILED) { + peg$savedPos = s0; + s1 = peg$c110(s2); + s0 = s1; + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + } else { + peg$currPos = s0; + s0 = peg$FAILED; + } + + peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; + + return s0; + } + + + function nth(n) { return { type: 'nth-child', index: { type: 'literal', value: n } }; } + function nthLast(n) { return { type: 'nth-last-child', index: { type: 'literal', value: n } }; } + function strUnescape(s) { + return s.replace(/\\(.)/g, function(match, ch) { + switch(ch) { + case 'b': return '\b'; + case 'f': return '\f'; + case 'n': return '\n'; + case 'r': return '\r'; + case 't': return '\t'; + case 'v': return '\v'; + default: return ch; + } + }); + } + + + peg$result = peg$startRuleFunction(); + + if (peg$result !== peg$FAILED && peg$currPos === input.length) { + return peg$result; + } else { + if (peg$result !== peg$FAILED && peg$currPos < input.length) { + peg$fail(peg$endExpectation()); + } + + throw peg$buildStructuredError( + peg$maxFailExpected, + peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, + peg$maxFailPos < input.length + ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) + : peg$computeLocation(peg$maxFailPos, peg$maxFailPos) + ); + } + } + + return { + SyntaxError: peg$SyntaxError, + parse: peg$parse + }; +}); diff --git a/node_modules/esrecurse/.babelrc b/node_modules/esrecurse/.babelrc new file mode 100644 index 0000000000000000000000000000000000000000..a0765e185d3b6a76f50929c6e2482e3aa4526343 --- /dev/null +++ b/node_modules/esrecurse/.babelrc @@ -0,0 +1,3 @@ +{ + "presets": ["es2015"] +} diff --git a/node_modules/esrecurse/README.md b/node_modules/esrecurse/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ffea6b434a4a633020ae0c35c729772069be0f16 --- /dev/null +++ b/node_modules/esrecurse/README.md @@ -0,0 +1,171 @@ +### Esrecurse [![Build Status](https://travis-ci.org/estools/esrecurse.svg?branch=master)](https://travis-ci.org/estools/esrecurse) + +Esrecurse ([esrecurse](https://github.com/estools/esrecurse)) is +[ECMAScript](https://www.ecma-international.org/publications/standards/Ecma-262.htm) +recursive traversing functionality. + +### Example Usage + +The following code will output all variables declared at the root of a file. + +```javascript +esrecurse.visit(ast, { + XXXStatement: function (node) { + this.visit(node.left); + // do something... + this.visit(node.right); + } +}); +``` + +We can use `Visitor` instance. + +```javascript +var visitor = new esrecurse.Visitor({ + XXXStatement: function (node) { + this.visit(node.left); + // do something... + this.visit(node.right); + } +}); + +visitor.visit(ast); +``` + +We can inherit `Visitor` instance easily. + +```javascript +class Derived extends esrecurse.Visitor { + constructor() + { + super(null); + } + + XXXStatement(node) { + } +} +``` + +```javascript +function DerivedVisitor() { + esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */); +} +util.inherits(DerivedVisitor, esrecurse.Visitor); +DerivedVisitor.prototype.XXXStatement = function (node) { + this.visit(node.left); + // do something... + this.visit(node.right); +}; +``` + +And you can invoke default visiting operation inside custom visit operation. + +```javascript +function DerivedVisitor() { + esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */); +} +util.inherits(DerivedVisitor, esrecurse.Visitor); +DerivedVisitor.prototype.XXXStatement = function (node) { + // do something... + this.visitChildren(node); +}; +``` + +The `childVisitorKeys` option does customize the behaviour of `this.visitChildren(node)`. +We can use user-defined node types. + +```javascript +// This tree contains a user-defined `TestExpression` node. +var tree = { + type: 'TestExpression', + + // This 'argument' is the property containing the other **node**. + argument: { + type: 'Literal', + value: 20 + }, + + // This 'extended' is the property not containing the other **node**. + extended: true +}; +esrecurse.visit( + ast, + { + Literal: function (node) { + // do something... + } + }, + { + // Extending the existing traversing rules. + childVisitorKeys: { + // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] + TestExpression: ['argument'] + } + } +); +``` + +We can use the `fallback` option as well. +If the `fallback` option is `"iteration"`, `esrecurse` would visit all enumerable properties of unknown nodes. +Please note circular references cause the stack overflow. AST might have circular references in additional properties for some purpose (e.g. `node.parent`). + +```javascript +esrecurse.visit( + ast, + { + Literal: function (node) { + // do something... + } + }, + { + fallback: 'iteration' + } +); +``` + +If the `fallback` option is a function, `esrecurse` calls this function to determine the enumerable properties of unknown nodes. +Please note circular references cause the stack overflow. AST might have circular references in additional properties for some purpose (e.g. `node.parent`). + +```javascript +esrecurse.visit( + ast, + { + Literal: function (node) { + // do something... + } + }, + { + fallback: function (node) { + return Object.keys(node).filter(function(key) { + return key !== 'argument' + }); + } + } +); +``` + +### License + +Copyright (C) 2014 [Yusuke Suzuki](https://github.com/Constellation) + (twitter: [@Constellation](https://twitter.com/Constellation)) and other contributors. + +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. + +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 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. diff --git a/node_modules/esrecurse/esrecurse.js b/node_modules/esrecurse/esrecurse.js new file mode 100644 index 0000000000000000000000000000000000000000..15d57dfd0218f66036a7cb5c5fe8e18c26d82267 --- /dev/null +++ b/node_modules/esrecurse/esrecurse.js @@ -0,0 +1,117 @@ +/* + Copyright (C) 2014 Yusuke Suzuki + + 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. + + 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 BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +(function () { + 'use strict'; + + var estraverse = require('estraverse'); + + function isNode(node) { + if (node == null) { + return false; + } + return typeof node === 'object' && typeof node.type === 'string'; + } + + function isProperty(nodeType, key) { + return (nodeType === estraverse.Syntax.ObjectExpression || nodeType === estraverse.Syntax.ObjectPattern) && key === 'properties'; + } + + function Visitor(visitor, options) { + options = options || {}; + + this.__visitor = visitor || this; + this.__childVisitorKeys = options.childVisitorKeys + ? Object.assign({}, estraverse.VisitorKeys, options.childVisitorKeys) + : estraverse.VisitorKeys; + if (options.fallback === 'iteration') { + this.__fallback = Object.keys; + } else if (typeof options.fallback === 'function') { + this.__fallback = options.fallback; + } + } + + /* Default method for visiting children. + * When you need to call default visiting operation inside custom visiting + * operation, you can use it with `this.visitChildren(node)`. + */ + Visitor.prototype.visitChildren = function (node) { + var type, children, i, iz, j, jz, child; + + if (node == null) { + return; + } + + type = node.type || estraverse.Syntax.Property; + + children = this.__childVisitorKeys[type]; + if (!children) { + if (this.__fallback) { + children = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + type + '.'); + } + } + + for (i = 0, iz = children.length; i < iz; ++i) { + child = node[children[i]]; + if (child) { + if (Array.isArray(child)) { + for (j = 0, jz = child.length; j < jz; ++j) { + if (child[j]) { + if (isNode(child[j]) || isProperty(type, children[i])) { + this.visit(child[j]); + } + } + } + } else if (isNode(child)) { + this.visit(child); + } + } + } + }; + + /* Dispatching node. */ + Visitor.prototype.visit = function (node) { + var type; + + if (node == null) { + return; + } + + type = node.type || estraverse.Syntax.Property; + if (this.__visitor[type]) { + this.__visitor[type].call(this, node); + return; + } + this.visitChildren(node); + }; + + exports.version = require('./package.json').version; + exports.Visitor = Visitor; + exports.visit = function (node, visitor, options) { + var v = new Visitor(visitor, options); + v.visit(node); + }; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/esrecurse/gulpfile.babel.js b/node_modules/esrecurse/gulpfile.babel.js new file mode 100644 index 0000000000000000000000000000000000000000..aa881c9c3eaae5fac04467363abaac9e856bffde --- /dev/null +++ b/node_modules/esrecurse/gulpfile.babel.js @@ -0,0 +1,92 @@ +// Copyright (C) 2014 Yusuke Suzuki +// +// 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. +// +// 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 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. + +import gulp from 'gulp'; +import mocha from 'gulp-mocha'; +import eslint from 'gulp-eslint'; +import minimist from 'minimist'; +import git from 'gulp-git'; +import bump from 'gulp-bump'; +import filter from 'gulp-filter'; +import tagVersion from 'gulp-tag-version'; +import 'babel-register'; + +const SOURCE = [ + '*.js' +]; + +let ESLINT_OPTION = { + parser: 'babel-eslint', + parserOptions: { + 'sourceType': 'module' + }, + rules: { + 'quotes': 0, + 'eqeqeq': 0, + 'no-use-before-define': 0, + 'no-shadow': 0, + 'no-new': 0, + 'no-underscore-dangle': 0, + 'no-multi-spaces': 0, + 'no-native-reassign': 0, + 'no-loop-func': 0 + }, + env: { + 'node': true + } +}; + +gulp.task('test', function() { + let options = minimist(process.argv.slice(2), { + string: 'test', + default: { + test: 'test/*.js' + } + } + ); + return gulp.src(options.test).pipe(mocha({reporter: 'spec'})); +}); + +gulp.task('lint', () => + gulp.src(SOURCE) + .pipe(eslint(ESLINT_OPTION)) + .pipe(eslint.formatEach('stylish', process.stderr)) + .pipe(eslint.failOnError()) +); + +let inc = importance => + gulp.src(['./package.json']) + .pipe(bump({type: importance})) + .pipe(gulp.dest('./')) + .pipe(git.commit('Bumps package version')) + .pipe(filter('package.json')) + .pipe(tagVersion({ + prefix: '' + })) +; + +gulp.task('travis', [ 'lint', 'test' ]); +gulp.task('default', [ 'travis' ]); + +gulp.task('patch', [ ], () => inc('patch')); +gulp.task('minor', [ ], () => inc('minor')); +gulp.task('major', [ ], () => inc('major')); diff --git a/node_modules/esrecurse/package.json b/node_modules/esrecurse/package.json new file mode 100644 index 0000000000000000000000000000000000000000..dec5b1bc1fd3ac43e74d7a575cc6bb98b453b2e3 --- /dev/null +++ b/node_modules/esrecurse/package.json @@ -0,0 +1,52 @@ +{ + "name": "esrecurse", + "description": "ECMAScript AST recursive visitor", + "homepage": "https://github.com/estools/esrecurse", + "main": "esrecurse.js", + "version": "4.3.0", + "engines": { + "node": ">=4.0" + }, + "maintainers": [ + { + "name": "Yusuke Suzuki", + "email": "utatane.tea@gmail.com", + "web": "https://github.com/Constellation" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/estools/esrecurse.git" + }, + "dependencies": { + "estraverse": "^5.2.0" + }, + "devDependencies": { + "babel-cli": "^6.24.1", + "babel-eslint": "^7.2.3", + "babel-preset-es2015": "^6.24.1", + "babel-register": "^6.24.1", + "chai": "^4.0.2", + "esprima": "^4.0.0", + "gulp": "^3.9.0", + "gulp-bump": "^2.7.0", + "gulp-eslint": "^4.0.0", + "gulp-filter": "^5.0.0", + "gulp-git": "^2.4.1", + "gulp-mocha": "^4.3.1", + "gulp-tag-version": "^1.2.1", + "jsdoc": "^3.3.0-alpha10", + "minimist": "^1.1.0" + }, + "license": "BSD-2-Clause", + "scripts": { + "test": "gulp travis", + "unit-test": "gulp test", + "lint": "gulp lint" + }, + "babel": { + "presets": [ + "es2015" + ] + } +} diff --git a/node_modules/estraverse/.jshintrc b/node_modules/estraverse/.jshintrc new file mode 100644 index 0000000000000000000000000000000000000000..f642dae7683b8155bd800db2aa3bfd574c2f7b64 --- /dev/null +++ b/node_modules/estraverse/.jshintrc @@ -0,0 +1,16 @@ +{ + "curly": true, + "eqeqeq": true, + "immed": true, + "eqnull": true, + "latedef": true, + "noarg": true, + "noempty": true, + "quotmark": "single", + "undef": true, + "unused": true, + "strict": true, + "trailing": true, + + "node": true +} diff --git a/node_modules/estraverse/LICENSE.BSD b/node_modules/estraverse/LICENSE.BSD new file mode 100644 index 0000000000000000000000000000000000000000..3e580c355a96e5ab8c4fb2ea4ada2d62287de41f --- /dev/null +++ b/node_modules/estraverse/LICENSE.BSD @@ -0,0 +1,19 @@ +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. + +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 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. diff --git a/node_modules/estraverse/README.md b/node_modules/estraverse/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ccd3377f3e9449547787f8f8f969def96e3f6d23 --- /dev/null +++ b/node_modules/estraverse/README.md @@ -0,0 +1,153 @@ +### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse) + +Estraverse ([estraverse](http://github.com/estools/estraverse)) is +[ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) +traversal functions from [esmangle project](http://github.com/estools/esmangle). + +### Documentation + +You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage). + +### Example Usage + +The following code will output all variables declared at the root of a file. + +```javascript +estraverse.traverse(ast, { + enter: function (node, parent) { + if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') + return estraverse.VisitorOption.Skip; + }, + leave: function (node, parent) { + if (node.type == 'VariableDeclarator') + console.log(node.id.name); + } +}); +``` + +We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break. + +```javascript +estraverse.traverse(ast, { + enter: function (node) { + this.break(); + } +}); +``` + +And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. + +```javascript +result = estraverse.replace(tree, { + enter: function (node) { + // Replace it with replaced. + if (node.type === 'Literal') + return replaced; + } +}); +``` + +By passing `visitor.keys` mapping, we can extend estraverse traversing functionality. + +```javascript +// This tree contains a user-defined `TestExpression` node. +var tree = { + type: 'TestExpression', + + // This 'argument' is the property containing the other **node**. + argument: { + type: 'Literal', + value: 20 + }, + + // This 'extended' is the property not containing the other **node**. + extended: true +}; +estraverse.traverse(tree, { + enter: function (node) { }, + + // Extending the existing traversing rules. + keys: { + // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] + TestExpression: ['argument'] + } +}); +``` + +By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes. + +```javascript +// This tree contains a user-defined `TestExpression` node. +var tree = { + type: 'TestExpression', + + // This 'argument' is the property containing the other **node**. + argument: { + type: 'Literal', + value: 20 + }, + + // This 'extended' is the property not containing the other **node**. + extended: true +}; +estraverse.traverse(tree, { + enter: function (node) { }, + + // Iterating the child **nodes** of unknown nodes. + fallback: 'iteration' +}); +``` + +When `visitor.fallback` is a function, we can determine which keys to visit on each node. + +```javascript +// This tree contains a user-defined `TestExpression` node. +var tree = { + type: 'TestExpression', + + // This 'argument' is the property containing the other **node**. + argument: { + type: 'Literal', + value: 20 + }, + + // This 'extended' is the property not containing the other **node**. + extended: true +}; +estraverse.traverse(tree, { + enter: function (node) { }, + + // Skip the `argument` property of each node + fallback: function(node) { + return Object.keys(node).filter(function(key) { + return key !== 'argument'; + }); + } +}); +``` + +### License + +Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation) + (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. + +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. + +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 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. diff --git a/node_modules/estraverse/estraverse.js b/node_modules/estraverse/estraverse.js new file mode 100644 index 0000000000000000000000000000000000000000..f0d9af9b46bfebb6cda551de17beeb659c7a2f69 --- /dev/null +++ b/node_modules/estraverse/estraverse.js @@ -0,0 +1,805 @@ +/* + Copyright (C) 2012-2013 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat + + 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. + + 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 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. +*/ +/*jslint vars:false, bitwise:true*/ +/*jshint indent:4*/ +/*global exports:true*/ +(function clone(exports) { + 'use strict'; + + var Syntax, + VisitorOption, + VisitorKeys, + BREAK, + SKIP, + REMOVE; + + function deepCopy(obj) { + var ret = {}, key, val; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + val = obj[key]; + if (typeof val === 'object' && val !== null) { + ret[key] = deepCopy(val); + } else { + ret[key] = val; + } + } + } + return ret; + } + + // based on LLVM libc++ upper_bound / lower_bound + // MIT License + + function upperBound(array, func) { + var diff, len, i, current; + + len = array.length; + i = 0; + + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + len = diff; + } else { + i = current + 1; + len -= diff + 1; + } + } + return i; + } + + Syntax = { + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7. + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ChainExpression: 'ChainExpression', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7. + ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7. + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DebuggerStatement: 'DebuggerStatement', + DirectiveStatement: 'DirectiveStatement', + DoWhileStatement: 'DoWhileStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + ForOfStatement: 'ForOfStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7. + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportExpression: 'ImportExpression', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MetaProperty: 'MetaProperty', + MethodDefinition: 'MethodDefinition', + ModuleSpecifier: 'ModuleSpecifier', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + PrivateIdentifier: 'PrivateIdentifier', + Program: 'Program', + Property: 'Property', + PropertyDefinition: 'PropertyDefinition', + RestElement: 'RestElement', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + Super: 'Super', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; + + VisitorKeys = { + AssignmentExpression: ['left', 'right'], + AssignmentPattern: ['left', 'right'], + ArrayExpression: ['elements'], + ArrayPattern: ['elements'], + ArrowFunctionExpression: ['params', 'body'], + AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7. + BlockStatement: ['body'], + BinaryExpression: ['left', 'right'], + BreakStatement: ['label'], + CallExpression: ['callee', 'arguments'], + CatchClause: ['param', 'body'], + ChainExpression: ['expression'], + ClassBody: ['body'], + ClassDeclaration: ['id', 'superClass', 'body'], + ClassExpression: ['id', 'superClass', 'body'], + ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7. + ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + ConditionalExpression: ['test', 'consequent', 'alternate'], + ContinueStatement: ['label'], + DebuggerStatement: [], + DirectiveStatement: [], + DoWhileStatement: ['body', 'test'], + EmptyStatement: [], + ExportAllDeclaration: ['source'], + ExportDefaultDeclaration: ['declaration'], + ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], + ExportSpecifier: ['exported', 'local'], + ExpressionStatement: ['expression'], + ForStatement: ['init', 'test', 'update', 'body'], + ForInStatement: ['left', 'right', 'body'], + ForOfStatement: ['left', 'right', 'body'], + FunctionDeclaration: ['id', 'params', 'body'], + FunctionExpression: ['id', 'params', 'body'], + GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + Identifier: [], + IfStatement: ['test', 'consequent', 'alternate'], + ImportExpression: ['source'], + ImportDeclaration: ['specifiers', 'source'], + ImportDefaultSpecifier: ['local'], + ImportNamespaceSpecifier: ['local'], + ImportSpecifier: ['imported', 'local'], + Literal: [], + LabeledStatement: ['label', 'body'], + LogicalExpression: ['left', 'right'], + MemberExpression: ['object', 'property'], + MetaProperty: ['meta', 'property'], + MethodDefinition: ['key', 'value'], + ModuleSpecifier: [], + NewExpression: ['callee', 'arguments'], + ObjectExpression: ['properties'], + ObjectPattern: ['properties'], + PrivateIdentifier: [], + Program: ['body'], + Property: ['key', 'value'], + PropertyDefinition: ['key', 'value'], + RestElement: [ 'argument' ], + ReturnStatement: ['argument'], + SequenceExpression: ['expressions'], + SpreadElement: ['argument'], + Super: [], + SwitchStatement: ['discriminant', 'cases'], + SwitchCase: ['test', 'consequent'], + TaggedTemplateExpression: ['tag', 'quasi'], + TemplateElement: [], + TemplateLiteral: ['quasis', 'expressions'], + ThisExpression: [], + ThrowStatement: ['argument'], + TryStatement: ['block', 'handler', 'finalizer'], + UnaryExpression: ['argument'], + UpdateExpression: ['argument'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + WhileStatement: ['test', 'body'], + WithStatement: ['object', 'body'], + YieldExpression: ['argument'] + }; + + // unique id + BREAK = {}; + SKIP = {}; + REMOVE = {}; + + VisitorOption = { + Break: BREAK, + Skip: SKIP, + Remove: REMOVE + }; + + function Reference(parent, key) { + this.parent = parent; + this.key = key; + } + + Reference.prototype.replace = function replace(node) { + this.parent[this.key] = node; + }; + + Reference.prototype.remove = function remove() { + if (Array.isArray(this.parent)) { + this.parent.splice(this.key, 1); + return true; + } else { + this.replace(null); + return false; + } + }; + + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } + + function Controller() { } + + // API: + // return property path array from root to current node + Controller.prototype.path = function path() { + var i, iz, j, jz, result, element; + + function addToPath(result, path) { + if (Array.isArray(path)) { + for (j = 0, jz = path.length; j < jz; ++j) { + result.push(path[j]); + } + } else { + result.push(path); + } + } + + // root node + if (!this.__current.path) { + return null; + } + + // first node is sentinel, second node is root element + result = []; + for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { + element = this.__leavelist[i]; + addToPath(result, element.path); + } + addToPath(result, this.__current.path); + return result; + }; + + // API: + // return type of current node + Controller.prototype.type = function () { + var node = this.current(); + return node.type || this.__current.wrap; + }; + + // API: + // return array of parent elements + Controller.prototype.parents = function parents() { + var i, iz, result; + + // first node is sentinel + result = []; + for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { + result.push(this.__leavelist[i].node); + } + + return result; + }; + + // API: + // return current node + Controller.prototype.current = function current() { + return this.__current.node; + }; + + Controller.prototype.__execute = function __execute(callback, element) { + var previous, result; + + result = undefined; + + previous = this.__current; + this.__current = element; + this.__state = null; + if (callback) { + result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); + } + this.__current = previous; + + return result; + }; + + // API: + // notify control skip / break + Controller.prototype.notify = function notify(flag) { + this.__state = flag; + }; + + // API: + // skip child nodes of current node + Controller.prototype.skip = function () { + this.notify(SKIP); + }; + + // API: + // break traversals + Controller.prototype['break'] = function () { + this.notify(BREAK); + }; + + // API: + // remove node + Controller.prototype.remove = function () { + this.notify(REMOVE); + }; + + Controller.prototype.__initialize = function(root, visitor) { + this.visitor = visitor; + this.root = root; + this.__worklist = []; + this.__leavelist = []; + this.__current = null; + this.__state = null; + this.__fallback = null; + if (visitor.fallback === 'iteration') { + this.__fallback = Object.keys; + } else if (typeof visitor.fallback === 'function') { + this.__fallback = visitor.fallback; + } + + this.__keys = VisitorKeys; + if (visitor.keys) { + this.__keys = Object.assign(Object.create(this.__keys), visitor.keys); + } + }; + + function isNode(node) { + if (node == null) { + return false; + } + return typeof node === 'object' && typeof node.type === 'string'; + } + + function isProperty(nodeType, key) { + return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; + } + + function candidateExistsInLeaveList(leavelist, candidate) { + for (var i = leavelist.length - 1; i >= 0; --i) { + if (leavelist[i].node === candidate) { + return true; + } + } + return false; + } + + Controller.prototype.traverse = function traverse(root, visitor) { + var worklist, + leavelist, + element, + node, + nodeType, + ret, + key, + current, + current2, + candidates, + candidate, + sentinel; + + this.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + worklist.push(new Element(root, null, null, null)); + leavelist.push(new Element(null, null, null, null)); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + ret = this.__execute(visitor.leave, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } + + if (element.node) { + + ret = this.__execute(visitor.enter, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + + worklist.push(sentinel); + leavelist.push(element); + + if (this.__state === SKIP || ret === SKIP) { + continue; + } + + node = element.node; + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + + if (candidateExistsInLeaveList(leavelist, candidate[current2])) { + continue; + } + + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', null); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, null); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + if (candidateExistsInLeaveList(leavelist, candidate)) { + continue; + } + + worklist.push(new Element(candidate, key, null, null)); + } + } + } + } + }; + + Controller.prototype.replace = function replace(root, visitor) { + var worklist, + leavelist, + node, + nodeType, + target, + element, + current, + current2, + candidates, + candidate, + sentinel, + outer, + key; + + function removeElem(element) { + var i, + key, + nextElem, + parent; + + if (element.ref.remove()) { + // When the reference is an element of an array. + key = element.ref.key; + parent = element.ref.parent; + + // If removed from array, then decrease following items' keys. + i = worklist.length; + while (i--) { + nextElem = worklist[i]; + if (nextElem.ref && nextElem.ref.parent === parent) { + if (nextElem.ref.key < key) { + break; + } + --nextElem.ref.key; + } + } + } + } + + this.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + outer = { + root: root + }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + target = this.__execute(visitor.leave, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + } + + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + } + + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + continue; + } + + target = this.__execute(visitor.enter, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + element.node = target; + } + + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + element.node = null; + } + + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + + // node may be null + node = element.node; + if (!node) { + continue; + } + + worklist.push(sentinel); + leavelist.push(element); + + if (this.__state === SKIP || target === SKIP) { + continue; + } + + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, new Reference(node, key))); + } + } + } + + return outer.root; + }; + + function traverse(root, visitor) { + var controller = new Controller(); + return controller.traverse(root, visitor); + } + + function replace(root, visitor) { + var controller = new Controller(); + return controller.replace(root, visitor); + } + + function extendCommentRange(comment, tokens) { + var target; + + target = upperBound(tokens, function search(token) { + return token.range[0] > comment.range[0]; + }); + + comment.extendedRange = [comment.range[0], comment.range[1]]; + + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } + + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } + + return comment; + } + + function attachComments(tree, providedComments, tokens) { + // At first, we should calculate extended comment ranges. + var comments = [], comment, len, i, cursor; + + if (!tree.range) { + throw new Error('attachComments needs range information'); + } + + // tokens array is empty, we attach comments to tree as 'leadingComments' + if (!tokens.length) { + if (providedComments.length) { + for (i = 0, len = providedComments.length; i < len; i += 1) { + comment = deepCopy(providedComments[i]); + comment.extendedRange = [0, tree.range[0]]; + comments.push(comment); + } + tree.leadingComments = comments; + } + return tree; + } + + for (i = 0, len = providedComments.length; i < len; i += 1) { + comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); + } + + // This is based on John Freeman's implementation. + cursor = 0; + traverse(tree, { + enter: function (node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (comment.extendedRange[1] > node.range[0]) { + break; + } + + if (comment.extendedRange[1] === node.range[0]) { + if (!node.leadingComments) { + node.leadingComments = []; + } + node.leadingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + cursor = 0; + traverse(tree, { + leave: function (node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (node.range[1] < comment.extendedRange[0]) { + break; + } + + if (node.range[1] === comment.extendedRange[0]) { + if (!node.trailingComments) { + node.trailingComments = []; + } + node.trailingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + return tree; + } + + exports.Syntax = Syntax; + exports.traverse = traverse; + exports.replace = replace; + exports.attachComments = attachComments; + exports.VisitorKeys = VisitorKeys; + exports.VisitorOption = VisitorOption; + exports.Controller = Controller; + exports.cloneEnvironment = function () { return clone({}); }; + + return exports; +}(exports)); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/estraverse/gulpfile.js b/node_modules/estraverse/gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..8772bbcca542a8dc43f1e08f55126ae24426f983 --- /dev/null +++ b/node_modules/estraverse/gulpfile.js @@ -0,0 +1,70 @@ +/* + Copyright (C) 2014 Yusuke Suzuki + + 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. + + 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 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. +*/ + +'use strict'; + +var gulp = require('gulp'), + git = require('gulp-git'), + bump = require('gulp-bump'), + filter = require('gulp-filter'), + tagVersion = require('gulp-tag-version'); + +var TEST = [ 'test/*.js' ]; +var POWERED = [ 'powered-test/*.js' ]; +var SOURCE = [ 'src/**/*.js' ]; + +/** + * Bumping version number and tagging the repository with it. + * Please read http://semver.org/ + * + * You can use the commands + * + * gulp patch # makes v0.1.0 -> v0.1.1 + * gulp feature # makes v0.1.1 -> v0.2.0 + * gulp release # makes v0.2.1 -> v1.0.0 + * + * To bump the version numbers accordingly after you did a patch, + * introduced a feature or made a backwards-incompatible release. + */ + +function inc(importance) { + // get all the files to bump version in + return gulp.src(['./package.json']) + // bump the version number in those files + .pipe(bump({type: importance})) + // save it back to filesystem + .pipe(gulp.dest('./')) + // commit the changed version number + .pipe(git.commit('Bumps package version')) + // read only one file to get the version number + .pipe(filter('package.json')) + // **tag it in the repository** + .pipe(tagVersion({ + prefix: '' + })); +} + +gulp.task('patch', [ ], function () { return inc('patch'); }) +gulp.task('minor', [ ], function () { return inc('minor'); }) +gulp.task('major', [ ], function () { return inc('major'); }) diff --git a/node_modules/estraverse/package.json b/node_modules/estraverse/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a86321850b4ec93883754e4de7b03227e1a9a379 --- /dev/null +++ b/node_modules/estraverse/package.json @@ -0,0 +1,40 @@ +{ + "name": "estraverse", + "description": "ECMAScript JS AST traversal functions", + "homepage": "https://github.com/estools/estraverse", + "main": "estraverse.js", + "version": "5.3.0", + "engines": { + "node": ">=4.0" + }, + "maintainers": [ + { + "name": "Yusuke Suzuki", + "email": "utatane.tea@gmail.com", + "web": "http://github.com/Constellation" + } + ], + "repository": { + "type": "git", + "url": "http://github.com/estools/estraverse.git" + }, + "devDependencies": { + "babel-preset-env": "^1.6.1", + "babel-register": "^6.3.13", + "chai": "^2.1.1", + "espree": "^1.11.0", + "gulp": "^3.8.10", + "gulp-bump": "^0.2.2", + "gulp-filter": "^2.0.0", + "gulp-git": "^1.0.1", + "gulp-tag-version": "^1.3.0", + "jshint": "^2.5.6", + "mocha": "^2.1.0" + }, + "license": "BSD-2-Clause", + "scripts": { + "test": "npm run-script lint && npm run-script unit-test", + "lint": "jshint estraverse.js", + "unit-test": "mocha --compilers js:babel-register" + } +} diff --git a/node_modules/estree-util-is-identifier-name/index.d.ts b/node_modules/estree-util-is-identifier-name/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..11a112cd7257676975a76eae0a9ab9d504052e30 --- /dev/null +++ b/node_modules/estree-util-is-identifier-name/index.d.ts @@ -0,0 +1,2 @@ +export type Options = import('./lib/index.js').Options; +export { cont, name, start } from "./lib/index.js"; diff --git a/node_modules/estree-util-is-identifier-name/index.js b/node_modules/estree-util-is-identifier-name/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a78d8fe5102db7f61d0cd7fd56bc2a749a863d54 --- /dev/null +++ b/node_modules/estree-util-is-identifier-name/index.js @@ -0,0 +1,5 @@ +/** + * @typedef {import('./lib/index.js').Options} Options + */ + +export {cont, name, start} from './lib/index.js' diff --git a/node_modules/estree-util-is-identifier-name/lib/index.d.ts b/node_modules/estree-util-is-identifier-name/lib/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fe2cd4d1938017e8e3aea15ea7ce6e6869ff1433 --- /dev/null +++ b/node_modules/estree-util-is-identifier-name/lib/index.d.ts @@ -0,0 +1,40 @@ +/** + * Checks if the given code point can start an identifier. + * + * @param {number | undefined} code + * Code point to check. + * @returns {boolean} + * Whether `code` can start an identifier. + */ +export function start(code: number | undefined): boolean; +/** + * Checks if the given code point can continue an identifier. + * + * @param {number | undefined} code + * Code point to check. + * @param {Options | null | undefined} [options] + * Configuration (optional). + * @returns {boolean} + * Whether `code` can continue an identifier. + */ +export function cont(code: number | undefined, options?: Options | null | undefined): boolean; +/** + * Checks if the given value is a valid identifier name. + * + * @param {string} name + * Identifier to check. + * @param {Options | null | undefined} [options] + * Configuration (optional). + * @returns {boolean} + * Whether `name` can be an identifier. + */ +export function name(name: string, options?: Options | null | undefined): boolean; +/** + * Configuration. + */ +export type Options = { + /** + * Support JSX identifiers (default: `false`). + */ + jsx?: boolean | null | undefined; +}; diff --git a/node_modules/estree-util-is-identifier-name/lib/index.js b/node_modules/estree-util-is-identifier-name/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d23d65dc7268113c1f28cb7b14d5961bc141f74b --- /dev/null +++ b/node_modules/estree-util-is-identifier-name/lib/index.js @@ -0,0 +1,61 @@ +/** + * @typedef Options + * Configuration. + * @property {boolean | null | undefined} [jsx=false] + * Support JSX identifiers (default: `false`). + */ + +const startRe = /[$_\p{ID_Start}]/u +const contRe = /[$_\u{200C}\u{200D}\p{ID_Continue}]/u +const contReJsx = /[-$_\u{200C}\u{200D}\p{ID_Continue}]/u +const nameRe = /^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u +const nameReJsx = /^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u + +/** @type {Options} */ +const emptyOptions = {} + +/** + * Checks if the given code point can start an identifier. + * + * @param {number | undefined} code + * Code point to check. + * @returns {boolean} + * Whether `code` can start an identifier. + */ +// Note: `undefined` is supported so you can pass the result from `''.codePointAt`. +export function start(code) { + return code ? startRe.test(String.fromCodePoint(code)) : false +} + +/** + * Checks if the given code point can continue an identifier. + * + * @param {number | undefined} code + * Code point to check. + * @param {Options | null | undefined} [options] + * Configuration (optional). + * @returns {boolean} + * Whether `code` can continue an identifier. + */ +// Note: `undefined` is supported so you can pass the result from `''.codePointAt`. +export function cont(code, options) { + const settings = options || emptyOptions + const re = settings.jsx ? contReJsx : contRe + return code ? re.test(String.fromCodePoint(code)) : false +} + +/** + * Checks if the given value is a valid identifier name. + * + * @param {string} name + * Identifier to check. + * @param {Options | null | undefined} [options] + * Configuration (optional). + * @returns {boolean} + * Whether `name` can be an identifier. + */ +export function name(name, options) { + const settings = options || emptyOptions + const re = settings.jsx ? nameReJsx : nameRe + return re.test(name) +} diff --git a/node_modules/estree-util-is-identifier-name/license b/node_modules/estree-util-is-identifier-name/license new file mode 100644 index 0000000000000000000000000000000000000000..39372356c47d0f6e070ff62d84c69f4f5e8c16eb --- /dev/null +++ b/node_modules/estree-util-is-identifier-name/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2020 Titus Wormer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/estree-util-is-identifier-name/package.json b/node_modules/estree-util-is-identifier-name/package.json new file mode 100644 index 0000000000000000000000000000000000000000..463567c40a2a438e38fe17bd8f780551a7120ba4 --- /dev/null +++ b/node_modules/estree-util-is-identifier-name/package.json @@ -0,0 +1,73 @@ +{ + "name": "estree-util-is-identifier-name", + "version": "3.0.0", + "description": "Check if something can be an ecmascript (javascript) identifier name", + "license": "MIT", + "keywords": [ + "estree", + "ast", + "ecmascript", + "javascript", + "tree", + "identifier", + "character" + ], + "repository": "syntax-tree/estree-util-is-identifier-name", + "bugs": "https://github.com/syntax-tree/estree-util-is-identifier-name/issues", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + }, + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "exports": "./index.js", + "files": [ + "lib/", + "index.d.ts", + "index.js" + ], + "devDependencies": { + "@types/node": "^20.0.0", + "c8": "^8.0.0", + "prettier": "^3.0.0", + "remark-cli": "^11.0.0", + "remark-preset-wooorm": "^9.0.0", + "type-coverage": "^2.0.0", + "typescript": "^5.0.0", + "xo": "^0.55.0" + }, + "scripts": { + "prepack": "npm run build && npm run format", + "build": "tsc --build --clean && tsc --build && type-coverage", + "format": "remark . -qfo && prettier . -w --log-level warn && xo --fix", + "test-api": "node --conditions development test.js", + "test-coverage": "c8 --100 --reporter lcov npm run test-api", + "test": "npm run build && npm run format && npm run test-coverage" + }, + "prettier": { + "bracketSpacing": false, + "semi": false, + "singleQuote": true, + "tabWidth": 2, + "trailingComma": "none", + "useTabs": false + }, + "remarkConfig": { + "plugins": [ + "remark-preset-wooorm" + ] + }, + "typeCoverage": { + "atLeast": 100, + "detail": true, + "ignoreCatch": true, + "strict": true + }, + "xo": { + "prettier": true + } +} diff --git a/node_modules/estree-util-is-identifier-name/readme.md b/node_modules/estree-util-is-identifier-name/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..9dce944473c7e31723ba3271c6450383bae5783b --- /dev/null +++ b/node_modules/estree-util-is-identifier-name/readme.md @@ -0,0 +1,225 @@ +# estree-util-is-identifier-name + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] +[![Sponsors][sponsors-badge]][collective] +[![Backers][backers-badge]][collective] +[![Chat][chat-badge]][chat] + +[estree][] utility to check if something can be an identifier. + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`cont(code[, options])`](#contcode-options) + * [`name(name[, options])`](#namename-options) + * [`start(code)`](#startcode) + * [Options](#options) +* [Types](#types) +* [Compatibility](#compatibility) +* [Related](#related) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This package is a utility that can be used to check if something can be an +identifier name. +For example, `a`, `_`, and `a1` are fine, but `1` and `-` are not. + +## When should I use this? + +You can use this utility when generating IDs from strings or parsing IDs. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 16+), install with [npm][]: + +```sh +npm install estree-util-is-identifier-name +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import {cont, name, start} from 'https://esm.sh/estree-util-is-identifier-name@3' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +import {cont, name, start} from 'estree-util-is-identifier-name' + +name('$something69') // => true +name('69') // => false +name('var') // => true (this does not handle keywords) + +start(48) // => false (code point for `'0'`) +cont(48) // => true (code point for `'0'`) +``` + +## API + +This package exports the identifiers [`cont`][api-cont], +[`name`][api-name], and +[`start`][api-start]. +There is no default export. + +### `cont(code[, options])` + +Checks if the given code point can continue an identifier. + +###### Parameters + +* `code` (`number`) + — code point to check +* `options` ([`Options`][api-options], optional) + — configuration + +###### Returns + +Whether `code` can continue an identifier (`boolean`). + +### `name(name[, options])` + +Checks if the given value is a valid identifier name. + +###### Parameters + +* `name` (`string`) + — identifier to check +* `options` ([`Options`][api-options], optional) + — configuration + +###### Returns + +Whether `name` can be an identifier (`boolean`). + +### `start(code)` + +Checks if the given code point can start an identifier. + +###### Parameters + +* `code` (`number`) + — code point to check + +###### Returns + +Whether `code` can start an identifier (`boolean`). + +### Options + +Configuration (TypeScript type). + +###### Fields + +* `jsx` (`boolean`, default: `false`) + — support JSX identifiers. + +## Types + +This package is fully typed with [TypeScript][]. +It exports the additional type [`Options`][api-options]. + +## Compatibility + +Projects maintained by the unified collective are compatible with maintained +versions of Node.js. + +When we cut a new major release, we drop support for unmaintained versions of +Node. +This means we try to keep the current release line, +`estree-util-is-identifier-name@^3`, compatible with Node.js 16. + +## Related + +* [`goto-bus-stop/estree-is-identifier`](https://github.com/goto-bus-stop/estree-is-identifier) + — check if an AST node is an identifier + +## Contribute + +See [`contributing.md`][contributing] in [`syntax-tree/.github`][health] for +ways to get started. +See [`support.md`][support] for ways to get help. + +This project has a [code of conduct][coc]. +By interacting with this repository, organization, or community you agree to +abide by its terms. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/syntax-tree/estree-util-is-identifier-name/workflows/main/badge.svg + +[build]: https://github.com/syntax-tree/estree-util-is-identifier-name/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/syntax-tree/estree-util-is-identifier-name.svg + +[coverage]: https://codecov.io/github/syntax-tree/estree-util-is-identifier-name + +[downloads-badge]: https://img.shields.io/npm/dm/estree-util-is-identifier-name.svg + +[downloads]: https://www.npmjs.com/package/estree-util-is-identifier-name + +[size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=estree-util-is-identifier-name + +[size]: https://bundlejs.com/?q=estree-util-is-identifier-name + +[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg + +[backers-badge]: https://opencollective.com/unified/backers/badge.svg + +[collective]: https://opencollective.com/unified + +[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg + +[chat]: https://github.com/syntax-tree/unist/discussions + +[npm]: https://docs.npmjs.com/cli/install + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[esmsh]: https://esm.sh + +[typescript]: https://www.typescriptlang.org + +[license]: license + +[author]: https://wooorm.com + +[health]: https://github.com/syntax-tree/.github + +[contributing]: https://github.com/syntax-tree/.github/blob/main/contributing.md + +[support]: https://github.com/syntax-tree/.github/blob/main/support.md + +[coc]: https://github.com/syntax-tree/.github/blob/main/code-of-conduct.md + +[estree]: https://github.com/estree/estree + +[api-cont]: #contcode-options + +[api-name]: #namename-options + +[api-start]: #startcode + +[api-options]: #options diff --git a/node_modules/estree-walker/LICENSE b/node_modules/estree-walker/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..63b62098eea9e1031659a145b1c6d752486ec0fe --- /dev/null +++ b/node_modules/estree-walker/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2015-20 [these people](https://github.com/Rich-Harris/estree-walker/graphs/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. \ No newline at end of file diff --git a/node_modules/estree-walker/README.md b/node_modules/estree-walker/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d739d1bf1811736d657775bdfdd261801bc92809 --- /dev/null +++ b/node_modules/estree-walker/README.md @@ -0,0 +1,48 @@ +# estree-walker + +Simple utility for walking an [ESTree](https://github.com/estree/estree)-compliant AST, such as one generated by [acorn](https://github.com/marijnh/acorn). + + +## Installation + +```bash +npm i estree-walker +``` + + +## Usage + +```js +var walk = require('estree-walker').walk; +var acorn = require('acorn'); + +ast = acorn.parse(sourceCode, options); // https://github.com/acornjs/acorn + +walk(ast, { + enter(node, parent, prop, index) { + // some code happens + }, + leave(node, parent, prop, index) { + // some code happens + } +}); +``` + +Inside the `enter` function, calling `this.skip()` will prevent the node's children being walked, or the `leave` function (which is optional) being called. + +Call `this.replace(new_node)` in either `enter` or `leave` to replace the current node with a new one. + +Call `this.remove()` in either `enter` or `leave` to remove the current node. + +## Why not use estraverse? + +The ESTree spec is evolving to accommodate ES6/7. I've had a couple of experiences where [estraverse](https://github.com/estools/estraverse) was unable to handle an AST generated by recent versions of acorn, because it hard-codes visitor keys. + +estree-walker, by contrast, simply enumerates a node's properties to find child nodes (and child lists of nodes), and is therefore resistant to spec changes. It's also much smaller. (The performance, if you're wondering, is basically identical.) + +None of which should be taken as criticism of estraverse, which has more features and has been battle-tested in many more situations, and for which I'm very grateful. + + +## License + +MIT diff --git a/node_modules/estree-walker/package.json b/node_modules/estree-walker/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c9f54edd9f394c267429a4b1393d67df42fbbe45 --- /dev/null +++ b/node_modules/estree-walker/package.json @@ -0,0 +1,38 @@ +{ + "name": "estree-walker", + "description": "Traverse an ESTree-compliant AST", + "version": "3.0.3", + "private": false, + "author": "Rich Harris", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/Rich-Harris/estree-walker" + }, + "type": "module", + "module": "./src/index.js", + "exports": { + "./package.json": "./package.json", + ".": { + "types": "./types/index.d.ts", + "import": "./src/index.js" + } + }, + "types": "types/index.d.ts", + "scripts": { + "prepublishOnly": "tsc && npm test", + "test": "uvu test" + }, + "dependencies": { + "@types/estree": "^1.0.0" + }, + "devDependencies": { + "typescript": "^4.9.0", + "uvu": "^0.5.1" + }, + "files": [ + "src", + "types", + "README.md" + ] +} diff --git a/node_modules/estree-walker/src/async.js b/node_modules/estree-walker/src/async.js new file mode 100644 index 0000000000000000000000000000000000000000..f068c713c4cdb2e57a2e98829b75e0541d943b9d --- /dev/null +++ b/node_modules/estree-walker/src/async.js @@ -0,0 +1,152 @@ +import { WalkerBase } from './walker.js'; + +/** + * @typedef { import('estree').Node} Node + * @typedef { import('./walker.js').WalkerContext} WalkerContext + * @typedef {( + * this: WalkerContext, + * node: Node, + * parent: Node | null, + * key: string | number | symbol | null | undefined, + * index: number | null | undefined + * ) => Promise} AsyncHandler + */ + +export class AsyncWalker extends WalkerBase { + /** + * + * @param {AsyncHandler} [enter] + * @param {AsyncHandler} [leave] + */ + constructor(enter, leave) { + super(); + + /** @type {boolean} */ + this.should_skip = false; + + /** @type {boolean} */ + this.should_remove = false; + + /** @type {Node | null} */ + this.replacement = null; + + /** @type {WalkerContext} */ + this.context = { + skip: () => (this.should_skip = true), + remove: () => (this.should_remove = true), + replace: (node) => (this.replacement = node) + }; + + /** @type {AsyncHandler | undefined} */ + this.enter = enter; + + /** @type {AsyncHandler | undefined} */ + this.leave = leave; + } + + /** + * @template {Node} Parent + * @param {Node} node + * @param {Parent | null} parent + * @param {keyof Parent} [prop] + * @param {number | null} [index] + * @returns {Promise} + */ + async visit(node, parent, prop, index) { + if (node) { + if (this.enter) { + const _should_skip = this.should_skip; + const _should_remove = this.should_remove; + const _replacement = this.replacement; + this.should_skip = false; + this.should_remove = false; + this.replacement = null; + + await this.enter.call(this.context, node, parent, prop, index); + + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop, index, node); + } + + if (this.should_remove) { + this.remove(parent, prop, index); + } + + const skipped = this.should_skip; + const removed = this.should_remove; + + this.should_skip = _should_skip; + this.should_remove = _should_remove; + this.replacement = _replacement; + + if (skipped) return node; + if (removed) return null; + } + + /** @type {keyof Node} */ + let key; + + for (key in node) { + /** @type {unknown} */ + const value = node[key]; + + if (value && typeof value === 'object') { + if (Array.isArray(value)) { + const nodes = /** @type {Array} */ (value); + for (let i = 0; i < nodes.length; i += 1) { + const item = nodes[i]; + if (isNode(item)) { + if (!(await this.visit(item, node, key, i))) { + // removed + i--; + } + } + } + } else if (isNode(value)) { + await this.visit(value, node, key, null); + } + } + } + + if (this.leave) { + const _replacement = this.replacement; + const _should_remove = this.should_remove; + this.replacement = null; + this.should_remove = false; + + await this.leave.call(this.context, node, parent, prop, index); + + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop, index, node); + } + + if (this.should_remove) { + this.remove(parent, prop, index); + } + + const removed = this.should_remove; + + this.replacement = _replacement; + this.should_remove = _should_remove; + + if (removed) return null; + } + } + + return node; + } +} + +/** + * Ducktype a node. + * + * @param {unknown} value + * @returns {value is Node} + */ +function isNode(value) { + return ( + value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string' + ); +} diff --git a/node_modules/estree-walker/src/index.js b/node_modules/estree-walker/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..933ea4f28ddb57cc53976aa5504d3ef39bbc0586 --- /dev/null +++ b/node_modules/estree-walker/src/index.js @@ -0,0 +1,34 @@ +import { SyncWalker } from './sync.js'; +import { AsyncWalker } from './async.js'; + +/** + * @typedef {import('estree').Node} Node + * @typedef {import('./sync.js').SyncHandler} SyncHandler + * @typedef {import('./async.js').AsyncHandler} AsyncHandler + */ + +/** + * @param {Node} ast + * @param {{ + * enter?: SyncHandler + * leave?: SyncHandler + * }} walker + * @returns {Node | null} + */ +export function walk(ast, { enter, leave }) { + const instance = new SyncWalker(enter, leave); + return instance.visit(ast, null); +} + +/** + * @param {Node} ast + * @param {{ + * enter?: AsyncHandler + * leave?: AsyncHandler + * }} walker + * @returns {Promise} + */ +export async function asyncWalk(ast, { enter, leave }) { + const instance = new AsyncWalker(enter, leave); + return await instance.visit(ast, null); +} diff --git a/node_modules/estree-walker/src/sync.js b/node_modules/estree-walker/src/sync.js new file mode 100644 index 0000000000000000000000000000000000000000..171fb360a76998c7b0e10a4544715a1be095c267 --- /dev/null +++ b/node_modules/estree-walker/src/sync.js @@ -0,0 +1,152 @@ +import { WalkerBase } from './walker.js'; + +/** + * @typedef { import('estree').Node} Node + * @typedef { import('./walker.js').WalkerContext} WalkerContext + * @typedef {( + * this: WalkerContext, + * node: Node, + * parent: Node | null, + * key: string | number | symbol | null | undefined, + * index: number | null | undefined + * ) => void} SyncHandler + */ + +export class SyncWalker extends WalkerBase { + /** + * + * @param {SyncHandler} [enter] + * @param {SyncHandler} [leave] + */ + constructor(enter, leave) { + super(); + + /** @type {boolean} */ + this.should_skip = false; + + /** @type {boolean} */ + this.should_remove = false; + + /** @type {Node | null} */ + this.replacement = null; + + /** @type {WalkerContext} */ + this.context = { + skip: () => (this.should_skip = true), + remove: () => (this.should_remove = true), + replace: (node) => (this.replacement = node) + }; + + /** @type {SyncHandler | undefined} */ + this.enter = enter; + + /** @type {SyncHandler | undefined} */ + this.leave = leave; + } + + /** + * @template {Node} Parent + * @param {Node} node + * @param {Parent | null} parent + * @param {keyof Parent} [prop] + * @param {number | null} [index] + * @returns {Node | null} + */ + visit(node, parent, prop, index) { + if (node) { + if (this.enter) { + const _should_skip = this.should_skip; + const _should_remove = this.should_remove; + const _replacement = this.replacement; + this.should_skip = false; + this.should_remove = false; + this.replacement = null; + + this.enter.call(this.context, node, parent, prop, index); + + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop, index, node); + } + + if (this.should_remove) { + this.remove(parent, prop, index); + } + + const skipped = this.should_skip; + const removed = this.should_remove; + + this.should_skip = _should_skip; + this.should_remove = _should_remove; + this.replacement = _replacement; + + if (skipped) return node; + if (removed) return null; + } + + /** @type {keyof Node} */ + let key; + + for (key in node) { + /** @type {unknown} */ + const value = node[key]; + + if (value && typeof value === 'object') { + if (Array.isArray(value)) { + const nodes = /** @type {Array} */ (value); + for (let i = 0; i < nodes.length; i += 1) { + const item = nodes[i]; + if (isNode(item)) { + if (!this.visit(item, node, key, i)) { + // removed + i--; + } + } + } + } else if (isNode(value)) { + this.visit(value, node, key, null); + } + } + } + + if (this.leave) { + const _replacement = this.replacement; + const _should_remove = this.should_remove; + this.replacement = null; + this.should_remove = false; + + this.leave.call(this.context, node, parent, prop, index); + + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop, index, node); + } + + if (this.should_remove) { + this.remove(parent, prop, index); + } + + const removed = this.should_remove; + + this.replacement = _replacement; + this.should_remove = _should_remove; + + if (removed) return null; + } + } + + return node; + } +} + +/** + * Ducktype a node. + * + * @param {unknown} value + * @returns {value is Node} + */ +function isNode(value) { + return ( + value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string' + ); +} diff --git a/node_modules/estree-walker/src/walker.js b/node_modules/estree-walker/src/walker.js new file mode 100644 index 0000000000000000000000000000000000000000..6dc6bd7bbe52ee4713bbfc89c25a8e884e1b205f --- /dev/null +++ b/node_modules/estree-walker/src/walker.js @@ -0,0 +1,61 @@ +/** + * @typedef { import('estree').Node} Node + * @typedef {{ + * skip: () => void; + * remove: () => void; + * replace: (node: Node) => void; + * }} WalkerContext + */ + +export class WalkerBase { + constructor() { + /** @type {boolean} */ + this.should_skip = false; + + /** @type {boolean} */ + this.should_remove = false; + + /** @type {Node | null} */ + this.replacement = null; + + /** @type {WalkerContext} */ + this.context = { + skip: () => (this.should_skip = true), + remove: () => (this.should_remove = true), + replace: (node) => (this.replacement = node) + }; + } + + /** + * @template {Node} Parent + * @param {Parent | null | undefined} parent + * @param {keyof Parent | null | undefined} prop + * @param {number | null | undefined} index + * @param {Node} node + */ + replace(parent, prop, index, node) { + if (parent && prop) { + if (index != null) { + /** @type {Array} */ (parent[prop])[index] = node; + } else { + /** @type {Node} */ (parent[prop]) = node; + } + } + } + + /** + * @template {Node} Parent + * @param {Parent | null | undefined} parent + * @param {keyof Parent | null | undefined} prop + * @param {number | null | undefined} index + */ + remove(parent, prop, index) { + if (parent && prop) { + if (index !== null && index !== undefined) { + /** @type {Array} */ (parent[prop]).splice(index, 1); + } else { + delete parent[prop]; + } + } + } +} diff --git a/node_modules/estree-walker/types/async.d.ts b/node_modules/estree-walker/types/async.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..db0825aa7bc81d386b07d4897636ad930ebe3bb5 --- /dev/null +++ b/node_modules/estree-walker/types/async.d.ts @@ -0,0 +1,36 @@ +/** + * @typedef { import('estree').Node} Node + * @typedef { import('./walker.js').WalkerContext} WalkerContext + * @typedef {( + * this: WalkerContext, + * node: Node, + * parent: Node | null, + * key: string | number | symbol | null | undefined, + * index: number | null | undefined + * ) => Promise} AsyncHandler + */ +export class AsyncWalker extends WalkerBase { + /** + * + * @param {AsyncHandler} [enter] + * @param {AsyncHandler} [leave] + */ + constructor(enter?: AsyncHandler | undefined, leave?: AsyncHandler | undefined); + /** @type {AsyncHandler | undefined} */ + enter: AsyncHandler | undefined; + /** @type {AsyncHandler | undefined} */ + leave: AsyncHandler | undefined; + /** + * @template {Node} Parent + * @param {Node} node + * @param {Parent | null} parent + * @param {keyof Parent} [prop] + * @param {number | null} [index] + * @returns {Promise} + */ + visit(node: Node, parent: Parent | null, prop?: keyof Parent | undefined, index?: number | null | undefined): Promise; +} +export type Node = import('estree').Node; +export type WalkerContext = import('./walker.js').WalkerContext; +export type AsyncHandler = (this: WalkerContext, node: Node, parent: Node | null, key: string | number | symbol | null | undefined, index: number | null | undefined) => Promise; +import { WalkerBase } from "./walker.js"; diff --git a/node_modules/estree-walker/types/index.d.ts b/node_modules/estree-walker/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c25afed98bca5bb3bcffd542a532c121d182d4e1 --- /dev/null +++ b/node_modules/estree-walker/types/index.d.ts @@ -0,0 +1,32 @@ +/** + * @typedef {import('estree').Node} Node + * @typedef {import('./sync.js').SyncHandler} SyncHandler + * @typedef {import('./async.js').AsyncHandler} AsyncHandler + */ +/** + * @param {Node} ast + * @param {{ + * enter?: SyncHandler + * leave?: SyncHandler + * }} walker + * @returns {Node | null} + */ +export function walk(ast: Node, { enter, leave }: { + enter?: SyncHandler; + leave?: SyncHandler; +}): Node | null; +/** + * @param {Node} ast + * @param {{ + * enter?: AsyncHandler + * leave?: AsyncHandler + * }} walker + * @returns {Promise} + */ +export function asyncWalk(ast: Node, { enter, leave }: { + enter?: AsyncHandler; + leave?: AsyncHandler; +}): Promise; +export type Node = import('estree').Node; +export type SyncHandler = import('./sync.js').SyncHandler; +export type AsyncHandler = import('./async.js').AsyncHandler; diff --git a/node_modules/estree-walker/types/sync.d.ts b/node_modules/estree-walker/types/sync.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3612b7ff424a6a78edb67f8bb1738443fbabf2a7 --- /dev/null +++ b/node_modules/estree-walker/types/sync.d.ts @@ -0,0 +1,36 @@ +/** + * @typedef { import('estree').Node} Node + * @typedef { import('./walker.js').WalkerContext} WalkerContext + * @typedef {( + * this: WalkerContext, + * node: Node, + * parent: Node | null, + * key: string | number | symbol | null | undefined, + * index: number | null | undefined + * ) => void} SyncHandler + */ +export class SyncWalker extends WalkerBase { + /** + * + * @param {SyncHandler} [enter] + * @param {SyncHandler} [leave] + */ + constructor(enter?: SyncHandler | undefined, leave?: SyncHandler | undefined); + /** @type {SyncHandler | undefined} */ + enter: SyncHandler | undefined; + /** @type {SyncHandler | undefined} */ + leave: SyncHandler | undefined; + /** + * @template {Node} Parent + * @param {Node} node + * @param {Parent | null} parent + * @param {keyof Parent} [prop] + * @param {number | null} [index] + * @returns {Node | null} + */ + visit(node: Node, parent: Parent | null, prop?: keyof Parent | undefined, index?: number | null | undefined): Node | null; +} +export type Node = import('estree').Node; +export type WalkerContext = import('./walker.js').WalkerContext; +export type SyncHandler = (this: WalkerContext, node: Node, parent: Node | null, key: string | number | symbol | null | undefined, index: number | null | undefined) => void; +import { WalkerBase } from "./walker.js"; diff --git a/node_modules/estree-walker/types/walker.d.ts b/node_modules/estree-walker/types/walker.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a3fa29c193ab01bccf4c50495230f7c1a091c375 --- /dev/null +++ b/node_modules/estree-walker/types/walker.d.ts @@ -0,0 +1,39 @@ +/** + * @typedef { import('estree').Node} Node + * @typedef {{ + * skip: () => void; + * remove: () => void; + * replace: (node: Node) => void; + * }} WalkerContext + */ +export class WalkerBase { + /** @type {boolean} */ + should_skip: boolean; + /** @type {boolean} */ + should_remove: boolean; + /** @type {Node | null} */ + replacement: Node | null; + /** @type {WalkerContext} */ + context: WalkerContext; + /** + * @template {Node} Parent + * @param {Parent | null | undefined} parent + * @param {keyof Parent | null | undefined} prop + * @param {number | null | undefined} index + * @param {Node} node + */ + replace(parent: Parent | null | undefined, prop: keyof Parent | null | undefined, index: number | null | undefined, node: Node): void; + /** + * @template {Node} Parent + * @param {Parent | null | undefined} parent + * @param {keyof Parent | null | undefined} prop + * @param {number | null | undefined} index + */ + remove(parent: Parent_1 | null | undefined, prop: keyof Parent_1 | null | undefined, index: number | null | undefined): void; +} +export type Node = import('estree').Node; +export type WalkerContext = { + skip: () => void; + remove: () => void; + replace: (node: Node) => void; +}; diff --git a/node_modules/esutils/LICENSE.BSD b/node_modules/esutils/LICENSE.BSD new file mode 100644 index 0000000000000000000000000000000000000000..3e580c355a96e5ab8c4fb2ea4ada2d62287de41f --- /dev/null +++ b/node_modules/esutils/LICENSE.BSD @@ -0,0 +1,19 @@ +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. + +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 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. diff --git a/node_modules/esutils/README.md b/node_modules/esutils/README.md new file mode 100644 index 0000000000000000000000000000000000000000..517526cfb99b972d9a9f34eecf6e8f4d34e77ede --- /dev/null +++ b/node_modules/esutils/README.md @@ -0,0 +1,174 @@ +### esutils [![Build Status](https://secure.travis-ci.org/estools/esutils.svg)](http://travis-ci.org/estools/esutils) +esutils ([esutils](http://github.com/estools/esutils)) is +utility box for ECMAScript language tools. + +### API + +### ast + +#### ast.isExpression(node) + +Returns true if `node` is an Expression as defined in ECMA262 edition 5.1 section +[11](https://es5.github.io/#x11). + +#### ast.isStatement(node) + +Returns true if `node` is a Statement as defined in ECMA262 edition 5.1 section +[12](https://es5.github.io/#x12). + +#### ast.isIterationStatement(node) + +Returns true if `node` is an IterationStatement as defined in ECMA262 edition +5.1 section [12.6](https://es5.github.io/#x12.6). + +#### ast.isSourceElement(node) + +Returns true if `node` is a SourceElement as defined in ECMA262 edition 5.1 +section [14](https://es5.github.io/#x14). + +#### ast.trailingStatement(node) + +Returns `Statement?` if `node` has trailing `Statement`. +```js +if (cond) + consequent; +``` +When taking this `IfStatement`, returns `consequent;` statement. + +#### ast.isProblematicIfStatement(node) + +Returns true if `node` is a problematic IfStatement. If `node` is a problematic `IfStatement`, `node` cannot be represented as an one on one JavaScript code. +```js +{ + type: 'IfStatement', + consequent: { + type: 'WithStatement', + body: { + type: 'IfStatement', + consequent: {type: 'EmptyStatement'} + } + }, + alternate: {type: 'EmptyStatement'} +} +``` +The above node cannot be represented as a JavaScript code, since the top level `else` alternate belongs to an inner `IfStatement`. + + +### code + +#### code.isDecimalDigit(code) + +Return true if provided code is decimal digit. + +#### code.isHexDigit(code) + +Return true if provided code is hexadecimal digit. + +#### code.isOctalDigit(code) + +Return true if provided code is octal digit. + +#### code.isWhiteSpace(code) + +Return true if provided code is white space. White space characters are formally defined in ECMA262. + +#### code.isLineTerminator(code) + +Return true if provided code is line terminator. Line terminator characters are formally defined in ECMA262. + +#### code.isIdentifierStart(code) + +Return true if provided code can be the first character of ECMA262 Identifier. They are formally defined in ECMA262. + +#### code.isIdentifierPart(code) + +Return true if provided code can be the trailing character of ECMA262 Identifier. They are formally defined in ECMA262. + +### keyword + +#### keyword.isKeywordES5(id, strict) + +Returns `true` if provided identifier string is a Keyword or Future Reserved Word +in ECMA262 edition 5.1. They are formally defined in ECMA262 sections +[7.6.1.1](http://es5.github.io/#x7.6.1.1) and [7.6.1.2](http://es5.github.io/#x7.6.1.2), +respectively. If the `strict` flag is truthy, this function additionally checks whether +`id` is a Keyword or Future Reserved Word under strict mode. + +#### keyword.isKeywordES6(id, strict) + +Returns `true` if provided identifier string is a Keyword or Future Reserved Word +in ECMA262 edition 6. They are formally defined in ECMA262 sections +[11.6.2.1](http://ecma-international.org/ecma-262/6.0/#sec-keywords) and +[11.6.2.2](http://ecma-international.org/ecma-262/6.0/#sec-future-reserved-words), +respectively. If the `strict` flag is truthy, this function additionally checks whether +`id` is a Keyword or Future Reserved Word under strict mode. + +#### keyword.isReservedWordES5(id, strict) + +Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 5.1. +They are formally defined in ECMA262 section [7.6.1](http://es5.github.io/#x7.6.1). +If the `strict` flag is truthy, this function additionally checks whether `id` +is a Reserved Word under strict mode. + +#### keyword.isReservedWordES6(id, strict) + +Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 6. +They are formally defined in ECMA262 section [11.6.2](http://ecma-international.org/ecma-262/6.0/#sec-reserved-words). +If the `strict` flag is truthy, this function additionally checks whether `id` +is a Reserved Word under strict mode. + +#### keyword.isRestrictedWord(id) + +Returns `true` if provided identifier string is one of `eval` or `arguments`. +They are restricted in strict mode code throughout ECMA262 edition 5.1 and +in ECMA262 edition 6 section [12.1.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers-static-semantics-early-errors). + +#### keyword.isIdentifierNameES5(id) + +Return true if provided identifier string is an IdentifierName as specified in +ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). + +#### keyword.isIdentifierNameES6(id) + +Return true if provided identifier string is an IdentifierName as specified in +ECMA262 edition 6 section [11.6](http://ecma-international.org/ecma-262/6.0/#sec-names-and-keywords). + +#### keyword.isIdentifierES5(id, strict) + +Return true if provided identifier string is an Identifier as specified in +ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). If the `strict` +flag is truthy, this function additionally checks whether `id` is an Identifier +under strict mode. + +#### keyword.isIdentifierES6(id, strict) + +Return true if provided identifier string is an Identifier as specified in +ECMA262 edition 6 section [12.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers). +If the `strict` flag is truthy, this function additionally checks whether `id` +is an Identifier under strict mode. + +### License + +Copyright (C) 2013 [Yusuke Suzuki](http://github.com/Constellation) + (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. + +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. + +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 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. diff --git a/node_modules/esutils/lib/ast.js b/node_modules/esutils/lib/ast.js new file mode 100644 index 0000000000000000000000000000000000000000..8faadae1ce736d3766bd0f5cfb50e3d654851aad --- /dev/null +++ b/node_modules/esutils/lib/ast.js @@ -0,0 +1,144 @@ +/* + Copyright (C) 2013 Yusuke Suzuki + + 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. + + 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 BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +(function () { + 'use strict'; + + function isExpression(node) { + if (node == null) { return false; } + switch (node.type) { + case 'ArrayExpression': + case 'AssignmentExpression': + case 'BinaryExpression': + case 'CallExpression': + case 'ConditionalExpression': + case 'FunctionExpression': + case 'Identifier': + case 'Literal': + case 'LogicalExpression': + case 'MemberExpression': + case 'NewExpression': + case 'ObjectExpression': + case 'SequenceExpression': + case 'ThisExpression': + case 'UnaryExpression': + case 'UpdateExpression': + return true; + } + return false; + } + + function isIterationStatement(node) { + if (node == null) { return false; } + switch (node.type) { + case 'DoWhileStatement': + case 'ForInStatement': + case 'ForStatement': + case 'WhileStatement': + return true; + } + return false; + } + + function isStatement(node) { + if (node == null) { return false; } + switch (node.type) { + case 'BlockStatement': + case 'BreakStatement': + case 'ContinueStatement': + case 'DebuggerStatement': + case 'DoWhileStatement': + case 'EmptyStatement': + case 'ExpressionStatement': + case 'ForInStatement': + case 'ForStatement': + case 'IfStatement': + case 'LabeledStatement': + case 'ReturnStatement': + case 'SwitchStatement': + case 'ThrowStatement': + case 'TryStatement': + case 'VariableDeclaration': + case 'WhileStatement': + case 'WithStatement': + return true; + } + return false; + } + + function isSourceElement(node) { + return isStatement(node) || node != null && node.type === 'FunctionDeclaration'; + } + + function trailingStatement(node) { + switch (node.type) { + case 'IfStatement': + if (node.alternate != null) { + return node.alternate; + } + return node.consequent; + + case 'LabeledStatement': + case 'ForStatement': + case 'ForInStatement': + case 'WhileStatement': + case 'WithStatement': + return node.body; + } + return null; + } + + function isProblematicIfStatement(node) { + var current; + + if (node.type !== 'IfStatement') { + return false; + } + if (node.alternate == null) { + return false; + } + current = node.consequent; + do { + if (current.type === 'IfStatement') { + if (current.alternate == null) { + return true; + } + } + current = trailingStatement(current); + } while (current); + + return false; + } + + module.exports = { + isExpression: isExpression, + isStatement: isStatement, + isIterationStatement: isIterationStatement, + isSourceElement: isSourceElement, + isProblematicIfStatement: isProblematicIfStatement, + + trailingStatement: trailingStatement + }; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/esutils/lib/code.js b/node_modules/esutils/lib/code.js new file mode 100644 index 0000000000000000000000000000000000000000..23136af91f9fbc9233c1632a224cb55f8cf16354 --- /dev/null +++ b/node_modules/esutils/lib/code.js @@ -0,0 +1,135 @@ +/* + Copyright (C) 2013-2014 Yusuke Suzuki + Copyright (C) 2014 Ivan Nikulin + + 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. + + 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 BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +(function () { + 'use strict'; + + var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; + + // See `tools/generate-identifier-regex.js`. + ES5Regex = { + // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierStart: + NonAsciiIdentifierStart: /[\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\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\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-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\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]/, + // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierPart: + NonAsciiIdentifierPart: /[\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\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u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F1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\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-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\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\u200C\u200D\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-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\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]/ + }; + + ES6Regex = { + // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierStart: + NonAsciiIdentifierStart: /[\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\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\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-\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\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-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\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\uAAB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DEC0-\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\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\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]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\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]|\uD87E[\uDC00-\uDE1D]/, + // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierPart: + NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\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\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\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\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\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\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\u1369-\u1371\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-\u19DA\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-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\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\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\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-\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\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\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-\u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DE8A-\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\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\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]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85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DDEF]/ + }; + + function isDecimalDigit(ch) { + return 0x30 <= ch && ch <= 0x39; // 0..9 + } + + function isHexDigit(ch) { + return 0x30 <= ch && ch <= 0x39 || // 0..9 + 0x61 <= ch && ch <= 0x66 || // a..f + 0x41 <= ch && ch <= 0x46; // A..F + } + + function isOctalDigit(ch) { + return ch >= 0x30 && ch <= 0x37; // 0..7 + } + + // 7.2 White Space + + NON_ASCII_WHITESPACES = [ + 0x1680, + 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, + 0x202F, 0x205F, + 0x3000, + 0xFEFF + ]; + + function isWhiteSpace(ch) { + return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || + ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0; + } + + // 7.3 Line Terminators + + function isLineTerminator(ch) { + return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029; + } + + // 7.6 Identifier Names and Identifiers + + function fromCodePoint(cp) { + if (cp <= 0xFFFF) { return String.fromCharCode(cp); } + var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800); + var cu2 = String.fromCharCode(((cp - 0x10000) % 0x400) + 0xDC00); + return cu1 + cu2; + } + + IDENTIFIER_START = new Array(0x80); + for(ch = 0; ch < 0x80; ++ch) { + IDENTIFIER_START[ch] = + ch >= 0x61 && ch <= 0x7A || // a..z + ch >= 0x41 && ch <= 0x5A || // A..Z + ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) + } + + IDENTIFIER_PART = new Array(0x80); + for(ch = 0; ch < 0x80; ++ch) { + IDENTIFIER_PART[ch] = + ch >= 0x61 && ch <= 0x7A || // a..z + ch >= 0x41 && ch <= 0x5A || // A..Z + ch >= 0x30 && ch <= 0x39 || // 0..9 + ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) + } + + function isIdentifierStartES5(ch) { + return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); + } + + function isIdentifierPartES5(ch) { + return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); + } + + function isIdentifierStartES6(ch) { + return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); + } + + function isIdentifierPartES6(ch) { + return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); + } + + module.exports = { + isDecimalDigit: isDecimalDigit, + isHexDigit: isHexDigit, + isOctalDigit: isOctalDigit, + isWhiteSpace: isWhiteSpace, + isLineTerminator: isLineTerminator, + isIdentifierStartES5: isIdentifierStartES5, + isIdentifierPartES5: isIdentifierPartES5, + isIdentifierStartES6: isIdentifierStartES6, + isIdentifierPartES6: isIdentifierPartES6 + }; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/esutils/lib/keyword.js b/node_modules/esutils/lib/keyword.js new file mode 100644 index 0000000000000000000000000000000000000000..13c8c6a967caf0492670526699ecc3d0f653c368 --- /dev/null +++ b/node_modules/esutils/lib/keyword.js @@ -0,0 +1,165 @@ +/* + Copyright (C) 2013 Yusuke Suzuki + + 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. + + 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 BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +(function () { + 'use strict'; + + var code = require('./code'); + + function isStrictModeReservedWordES6(id) { + switch (id) { + case 'implements': + case 'interface': + case 'package': + case 'private': + case 'protected': + case 'public': + case 'static': + case 'let': + return true; + default: + return false; + } + } + + function isKeywordES5(id, strict) { + // yield should not be treated as keyword under non-strict mode. + if (!strict && id === 'yield') { + return false; + } + return isKeywordES6(id, strict); + } + + function isKeywordES6(id, strict) { + if (strict && isStrictModeReservedWordES6(id)) { + return true; + } + + switch (id.length) { + case 2: + return (id === 'if') || (id === 'in') || (id === 'do'); + case 3: + return (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try'); + case 4: + return (id === 'this') || (id === 'else') || (id === 'case') || + (id === 'void') || (id === 'with') || (id === 'enum'); + case 5: + return (id === 'while') || (id === 'break') || (id === 'catch') || + (id === 'throw') || (id === 'const') || (id === 'yield') || + (id === 'class') || (id === 'super'); + case 6: + return (id === 'return') || (id === 'typeof') || (id === 'delete') || + (id === 'switch') || (id === 'export') || (id === 'import'); + case 7: + return (id === 'default') || (id === 'finally') || (id === 'extends'); + case 8: + return (id === 'function') || (id === 'continue') || (id === 'debugger'); + case 10: + return (id === 'instanceof'); + default: + return false; + } + } + + function isReservedWordES5(id, strict) { + return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict); + } + + function isReservedWordES6(id, strict) { + return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict); + } + + function isRestrictedWord(id) { + return id === 'eval' || id === 'arguments'; + } + + function isIdentifierNameES5(id) { + var i, iz, ch; + + if (id.length === 0) { return false; } + + ch = id.charCodeAt(0); + if (!code.isIdentifierStartES5(ch)) { + return false; + } + + for (i = 1, iz = id.length; i < iz; ++i) { + ch = id.charCodeAt(i); + if (!code.isIdentifierPartES5(ch)) { + return false; + } + } + return true; + } + + function decodeUtf16(lead, trail) { + return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; + } + + function isIdentifierNameES6(id) { + var i, iz, ch, lowCh, check; + + if (id.length === 0) { return false; } + + check = code.isIdentifierStartES6; + for (i = 0, iz = id.length; i < iz; ++i) { + ch = id.charCodeAt(i); + if (0xD800 <= ch && ch <= 0xDBFF) { + ++i; + if (i >= iz) { return false; } + lowCh = id.charCodeAt(i); + if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) { + return false; + } + ch = decodeUtf16(ch, lowCh); + } + if (!check(ch)) { + return false; + } + check = code.isIdentifierPartES6; + } + return true; + } + + function isIdentifierES5(id, strict) { + return isIdentifierNameES5(id) && !isReservedWordES5(id, strict); + } + + function isIdentifierES6(id, strict) { + return isIdentifierNameES6(id) && !isReservedWordES6(id, strict); + } + + module.exports = { + isKeywordES5: isKeywordES5, + isKeywordES6: isKeywordES6, + isReservedWordES5: isReservedWordES5, + isReservedWordES6: isReservedWordES6, + isRestrictedWord: isRestrictedWord, + isIdentifierNameES5: isIdentifierNameES5, + isIdentifierNameES6: isIdentifierNameES6, + isIdentifierES5: isIdentifierES5, + isIdentifierES6: isIdentifierES6 + }; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/esutils/lib/utils.js b/node_modules/esutils/lib/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..ce18faa6bc80fa12d4af19681dd3fce62a90aff1 --- /dev/null +++ b/node_modules/esutils/lib/utils.js @@ -0,0 +1,33 @@ +/* + Copyright (C) 2013 Yusuke Suzuki + + 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. + + 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 BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +(function () { + 'use strict'; + + exports.ast = require('./ast'); + exports.code = require('./code'); + exports.keyword = require('./keyword'); +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/node_modules/esutils/package.json b/node_modules/esutils/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8396f4cee3f7e83d4be21fdc6fe1d038635065b8 --- /dev/null +++ b/node_modules/esutils/package.json @@ -0,0 +1,44 @@ +{ + "name": "esutils", + "description": "utility box for ECMAScript language tools", + "homepage": "https://github.com/estools/esutils", + "main": "lib/utils.js", + "version": "2.0.3", + "engines": { + "node": ">=0.10.0" + }, + "directories": { + "lib": "./lib" + }, + "files": [ + "LICENSE.BSD", + "README.md", + "lib" + ], + "maintainers": [ + { + "name": "Yusuke Suzuki", + "email": "utatane.tea@gmail.com", + "web": "http://github.com/Constellation" + } + ], + "repository": { + "type": "git", + "url": "http://github.com/estools/esutils.git" + }, + "devDependencies": { + "chai": "~1.7.2", + "coffee-script": "~1.6.3", + "jshint": "2.6.3", + "mocha": "~2.2.1", + "regenerate": "~1.3.1", + "unicode-9.0.0": "~0.7.0" + }, + "license": "BSD-2-Clause", + "scripts": { + "test": "npm run-script lint && npm run-script unit-test", + "lint": "jshint lib/*.js", + "unit-test": "mocha --compilers coffee:coffee-script -R spec", + "generate-regex": "node tools/generate-identifier-regex.js" + } +} diff --git a/node_modules/expand-template/.travis.yml b/node_modules/expand-template/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..1335a7708efb37e472e538c41a3cea8ae0448b8f --- /dev/null +++ b/node_modules/expand-template/.travis.yml @@ -0,0 +1,6 @@ +language: node_js + +node_js: + - 6 + - 8 + - 10 diff --git a/node_modules/expand-template/LICENSE b/node_modules/expand-template/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..814aef41de034229843a37d775d123680f86ec39 --- /dev/null +++ b/node_modules/expand-template/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018 Lars-Magnus Skog + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/expand-template/README.md b/node_modules/expand-template/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b98aa480c3de9c778389740f7bbdae75a3357958 --- /dev/null +++ b/node_modules/expand-template/README.md @@ -0,0 +1,43 @@ +# expand-template + +> Expand placeholders in a template string. + +[![npm](https://img.shields.io/npm/v/expand-template.svg)](https://www.npmjs.com/package/expand-template) +![Node version](https://img.shields.io/node/v/expand-template.svg) +[![Build Status](https://travis-ci.org/ralphtheninja/expand-template.svg?branch=master)](https://travis-ci.org/ralphtheninja/expand-template) +[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com) + +## Install + +``` +$ npm i expand-template -S +``` + +## Usage + +Default functionality expands templates using `{}` as separators for string placeholders. + +```js +var expand = require('expand-template')() +var template = '{foo}/{foo}/{bar}/{bar}' +console.log(expand(template, { + foo: 'BAR', + bar: 'FOO' +})) +// -> BAR/BAR/FOO/FOO +``` + +Custom separators: + +```js +var expand = require('expand-template')({ sep: '[]' }) +var template = '[foo]/[foo]/[bar]/[bar]' +console.log(expand(template, { + foo: 'BAR', + bar: 'FOO' +})) +// -> BAR/BAR/FOO/FOO +``` + +## License +All code, unless stated otherwise, is dual-licensed under [`WTFPL`](http://www.wtfpl.net/txt/copying/) and [`MIT`](https://opensource.org/licenses/MIT). diff --git a/node_modules/expand-template/index.js b/node_modules/expand-template/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e182837c0ba2900e0c17a7138830cd953c229abe --- /dev/null +++ b/node_modules/expand-template/index.js @@ -0,0 +1,26 @@ +module.exports = function (opts) { + var sep = opts ? opts.sep : '{}' + var len = sep.length + + var whitespace = '\\s*' + var left = escape(sep.substring(0, len / 2)) + whitespace + var right = whitespace + escape(sep.substring(len / 2, len)) + + return function (template, values) { + Object.keys(values).forEach(function (key) { + var value = String(values[key]).replace(/\$/g, '$$$$') + template = template.replace(regExp(key), value) + }) + return template + } + + function escape (s) { + return [].map.call(s, function (char) { + return '\\' + char + }).join('') + } + + function regExp (key) { + return new RegExp(left + key + right, 'g') + } +} diff --git a/node_modules/expand-template/package.json b/node_modules/expand-template/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9a09656c054a183f14d07a648defc741eebd4745 --- /dev/null +++ b/node_modules/expand-template/package.json @@ -0,0 +1,29 @@ +{ + "name": "expand-template", + "version": "2.0.3", + "description": "Expand placeholders in a template string", + "main": "index.js", + "repository": { + "type": "git", + "url": "https://github.com/ralphtheninja/expand-template.git" + }, + "homepage": "https://github.com/ralphtheninja/expand-template", + "scripts": { + "test": "tape test.js && standard" + }, + "keywords": [ + "template", + "expand", + "replace" + ], + "author": "LM ", + "license": "(MIT OR WTFPL)", + "dependencies": {}, + "devDependencies": { + "standard": "^12.0.0", + "tape": "^4.2.2" + }, + "engines": { + "node": ">=6" + } +} diff --git a/node_modules/expand-template/test.js b/node_modules/expand-template/test.js new file mode 100644 index 0000000000000000000000000000000000000000..ba6ed871e28db07d4539cbd349bff72f0e34ee08 --- /dev/null +++ b/node_modules/expand-template/test.js @@ -0,0 +1,67 @@ +var test = require('tape') +var Expand = require('./') + +test('default expands {} placeholders', function (t) { + var expand = Expand() + t.equal(typeof expand, 'function', 'is a function') + t.equal(expand('{foo}/{bar}', { + foo: 'BAR', bar: 'FOO' + }), 'BAR/FOO') + t.equal(expand('{foo}{foo}{foo}', { + foo: 'FOO' + }), 'FOOFOOFOO', 'expands one placeholder many times') + t.end() +}) + +test('support for custom separators', function (t) { + var expand = Expand({ sep: '[]' }) + t.equal(expand('[foo]/[bar]', { + foo: 'BAR', bar: 'FOO' + }), 'BAR/FOO') + t.equal(expand('[foo][foo][foo]', { + foo: 'FOO' + }), 'FOOFOOFOO', 'expands one placeholder many times') + t.end() +}) + +test('support for longer custom separators', function (t) { + var expand = Expand({ sep: '[[]]' }) + t.equal(expand('[[foo]]/[[bar]]', { + foo: 'BAR', bar: 'FOO' + }), 'BAR/FOO') + t.equal(expand('[[foo]][[foo]][[foo]]', { + foo: 'FOO' + }), 'FOOFOOFOO', 'expands one placeholder many times') + t.end() +}) + +test('whitespace-insensitive', function (t) { + var expand = Expand({ sep: '[]' }) + t.equal(expand('[ foo ]/[ bar ]', { + foo: 'BAR', bar: 'FOO' + }), 'BAR/FOO') + t.equal(expand('[ foo ][ foo ][ foo]', { + foo: 'FOO' + }), 'FOOFOOFOO', 'expands one placeholder many times') + t.end() +}) + +test('dollar escape', function (t) { + var expand = Expand() + t.equal(expand('before {foo} after', { + foo: '$' + }), 'before $ after') + t.equal(expand('before {foo} after', { + foo: '$&' + }), 'before $& after') + t.equal(expand('before {foo} after', { + foo: '$`' + }), 'before $` after') + t.equal(expand('before {foo} after', { + foo: '$\'' + }), 'before $\' after') + t.equal(expand('before {foo} after', { + foo: '$0' + }), 'before $0 after') + t.end() +}) diff --git a/node_modules/expect-type/LICENSE b/node_modules/expect-type/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..deede247d2ad6336f8c231e6265be9acc1d221ad --- /dev/null +++ b/node_modules/expect-type/LICENSE @@ -0,0 +1,191 @@ + Copyright 2024 Misha Kaletsky + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/node_modules/expect-type/README.md b/node_modules/expect-type/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9aaf8ca0f81ec8fcb503192dc9714c56ba0f5da5 --- /dev/null +++ b/node_modules/expect-type/README.md @@ -0,0 +1,925 @@ +# expect-type + +[![CI](https://github.com/mmkal/expect-type/actions/workflows/ci.yml/badge.svg)](https://github.com/mmkal/expect-type/actions/workflows/ci.yml) +![npm](https://img.shields.io/npm/dt/expect-type) +[![X Follow](https://img.shields.io/twitter/follow/mmkal)](https://x.com/mmkalmmkal) + +Compile-time tests for types. Useful to make sure types don't regress into being overly permissive as changes go in over time. + +Similar to `expect`, but with type-awareness. Gives you access to several type-matchers that let you make assertions about the form of a reference or generic type parameter. + +```ts +import {expectTypeOf} from 'expect-type' +import {foo, bar} from '../foo' + +// make sure `foo` has type {a: number} +expectTypeOf(foo).toEqualTypeOf<{a: number}>() + +// make sure `bar` is a function taking a string: +expectTypeOf(bar).parameter(0).toBeString() +expectTypeOf(bar).returns.not.toBeAny() +``` + +It can be used in your existing test files (and is actually [built in to vitest](https://vitest.dev/guide/testing-types)). Or it can be used in any other type-checked file you'd like - it's built into existing tooling with no dependencies. No extra build step, cli tool, IDE extension, or lint plugin is needed. Just import the function and start writing tests. Failures will be at compile time - they'll appear in your IDE and when you run `tsc`. + +See below for lots more examples. + +## Contents + +- [Contents](#contents) +- [Installation and usage](#installation-and-usage) +- [Documentation](#documentation) + - [Features](#features) + - [Why is my assertion failing?](#why-is-my-assertion-failing) + - [Why is `.toMatchTypeOf` deprecated?](#why-is-tomatchtypeof-deprecated) + - [Internal type helpers](#internal-type-helpers) + - [Error messages](#error-messages) + - [Concrete "expected" objects vs type arguments](#concrete-expected-objects-vs-type-arguments) + - [Overloaded functions](#overloaded-functions) + - [Within test frameworks](#within-test-frameworks) + - [Vitest](#vitest) + - [Jest & `eslint-plugin-jest`](#jest--eslint-plugin-jest) + - [Limitations](#limitations) +- [Similar projects](#similar-projects) + - [Comparison](#comparison) +- [TypeScript backwards-compatibility](#typescript-backwards-compatibility) +- [Contributing](#contributing) + - [Documentation of limitations through tests](#documentation-of-limitations-through-tests) + + +## Installation and usage + +```cli +npm install expect-type --save-dev +``` + +```typescript +import {expectTypeOf} from 'expect-type' +``` + +## Documentation + +The `expectTypeOf` method takes a single argument or a generic type parameter. Neither it nor the functions chained off its return value have any meaningful runtime behaviour. The assertions you write will be _compile-time_ errors if they don't hold true. + +### Features + + +Check an object's type with `.toEqualTypeOf`: + +```typescript +expectTypeOf({a: 1}).toEqualTypeOf<{a: number}>() +``` + +`.toEqualTypeOf` can check that two concrete objects have equivalent types (note: when these assertions _fail_, the error messages can be less informative vs the generic type argument syntax above - see [error messages docs](#error-messages)): + +```typescript +expectTypeOf({a: 1}).toEqualTypeOf({a: 1}) +``` + +`.toEqualTypeOf` succeeds for objects with different values, but the same type: + +```typescript +expectTypeOf({a: 1}).toEqualTypeOf({a: 2}) +``` + +`.toEqualTypeOf` fails on excess properties: + +```typescript +// @ts-expect-error +expectTypeOf({a: 1, b: 1}).toEqualTypeOf<{a: number}>() +``` + +To allow for extra properties on an object type, use `.toMatchObjectType`. This is a strict check, but only on the subset of keys that are in the expected type: + +```typescript +expectTypeOf({a: 1, b: 1}).toMatchObjectType<{a: number}>() +``` + +`.toMatchObjectType` can check partial matches on deeply nested objects: + +```typescript +const user = { + email: 'a@b.com', + name: 'John Doe', + address: {street: '123 2nd St', city: 'New York', zip: '10001', state: 'NY', country: 'USA'}, +} + +expectTypeOf(user).toMatchObjectType<{name: string; address: {city: string}}>() +``` + +To check that a type extends another type, use `.toExtend`: + +```typescript +expectTypeOf('some string').toExtend() +// @ts-expect-error +expectTypeOf({a: 1}).toExtend<{b: number}>() +``` + +`.toExtend` can be used with object types, but `.toMatchObjectType` is usually a better choice when dealing with objects, since it's stricter: + +```typescript +expectTypeOf({a: 1, b: 2}).toExtend<{a: number}>() // avoid this +expectTypeOf({a: 1, b: 2}).toMatchObjectType<{a: number}>() // prefer this +``` + +`.toEqualTypeOf`, `.toMatchObjectType`, and `.toExtend` all fail on missing properties: + +```typescript +// @ts-expect-error +expectTypeOf({a: 1}).toEqualTypeOf<{a: number; b: number}>() +// @ts-expect-error +expectTypeOf({a: 1}).toMatchObjectType<{a: number; b: number}>() +// @ts-expect-error +expectTypeOf({a: 1}).toExtend<{a: number; b: number}>() +``` + +Another example of the difference between `.toExtend`, `.toMatchObjectType`, and `.toEqualTypeOf`. `.toExtend` can be used for "is-a" relationships: + +```typescript +type Fruit = {type: 'Fruit'; edible: boolean} +type Apple = {type: 'Fruit'; name: 'Apple'; edible: true} + +expectTypeOf().toExtend() + +// @ts-expect-error - the `editable` property isn't an exact match. In `Apple`, it's `true`, which extends `boolean`, but they're not identical. +expectTypeOf().toMatchObjectType() + +// @ts-expect-error - Apple is not an identical type to Fruit, it's a subtype +expectTypeOf().toEqualTypeOf() + +// @ts-expect-error - Apple is a Fruit, but not vice versa +expectTypeOf().toExtend() +``` + +Assertions can be inverted with `.not`: + +```typescript +expectTypeOf({a: 1}).not.toExtend<{b: 1}>() +expectTypeOf({a: 1}).not.toMatchObjectType<{b: 1}>() +``` + +`.not` can be easier than relying on `// @ts-expect-error`: + +```typescript +type Fruit = {type: 'Fruit'; edible: boolean} +type Apple = {type: 'Fruit'; name: 'Apple'; edible: true} + +expectTypeOf().toExtend() + +expectTypeOf().not.toExtend() +expectTypeOf().not.toEqualTypeOf() +``` + +Catch any/unknown/never types: + +```typescript +expectTypeOf().toBeUnknown() +expectTypeOf().toBeAny() +expectTypeOf().toBeNever() + +// @ts-expect-error +expectTypeOf().toBeNumber() +``` + +`.toEqualTypeOf` distinguishes between deeply-nested `any` and `unknown` properties: + +```typescript +expectTypeOf<{deeply: {nested: any}}>().not.toEqualTypeOf<{deeply: {nested: unknown}}>() +``` + +You can test for basic JavaScript types: + +```typescript +expectTypeOf(() => 1).toBeFunction() +expectTypeOf({}).toBeObject() +expectTypeOf([]).toBeArray() +expectTypeOf('').toBeString() +expectTypeOf(1).toBeNumber() +expectTypeOf(true).toBeBoolean() +expectTypeOf(() => {}).returns.toBeVoid() +expectTypeOf(Promise.resolve(123)).resolves.toBeNumber() +expectTypeOf(Symbol(1)).toBeSymbol() +expectTypeOf(1n).toBeBigInt() +``` + +`.toBe...` methods allow for types that extend the expected type: + +```typescript +expectTypeOf().toBeNumber() +expectTypeOf<1>().toBeNumber() + +expectTypeOf().toBeArray() +expectTypeOf().toBeArray() + +expectTypeOf().toBeString() +expectTypeOf<'foo'>().toBeString() + +expectTypeOf().toBeBoolean() +expectTypeOf().toBeBoolean() + +expectTypeOf().toBeBigInt() +expectTypeOf<0n>().toBeBigInt() +``` + +`.toBe...` methods protect against `any`: + +```typescript +const goodIntParser = (s: string) => Number.parseInt(s, 10) +const badIntParser = (s: string) => JSON.parse(s) // uh-oh - works at runtime if the input is a number, but return 'any' + +expectTypeOf(goodIntParser).returns.toBeNumber() +// @ts-expect-error - if you write a test like this, `.toBeNumber()` will let you know your implementation returns `any`. +expectTypeOf(badIntParser).returns.toBeNumber() +``` + +Nullable types: + +```typescript +expectTypeOf(undefined).toBeUndefined() +expectTypeOf(undefined).toBeNullable() +expectTypeOf(undefined).not.toBeNull() + +expectTypeOf(null).toBeNull() +expectTypeOf(null).toBeNullable() +expectTypeOf(null).not.toBeUndefined() + +expectTypeOf<1 | undefined>().toBeNullable() +expectTypeOf<1 | null>().toBeNullable() +expectTypeOf<1 | undefined | null>().toBeNullable() +``` + +More `.not` examples: + +```typescript +expectTypeOf(1).not.toBeUnknown() +expectTypeOf(1).not.toBeAny() +expectTypeOf(1).not.toBeNever() +expectTypeOf(1).not.toBeNull() +expectTypeOf(1).not.toBeUndefined() +expectTypeOf(1).not.toBeNullable() +expectTypeOf(1).not.toBeBigInt() +``` + +Detect assignability of unioned types: + +```typescript +expectTypeOf().toExtend() +expectTypeOf().not.toExtend() +``` + +Use `.extract` and `.exclude` to narrow down complex union types: + +```typescript +type ResponsiveProp = T | T[] | {xs?: T; sm?: T; md?: T} +const getResponsiveProp = (_props: T): ResponsiveProp => ({}) +type CSSProperties = {margin?: string; padding?: string} + +const cssProperties: CSSProperties = {margin: '1px', padding: '2px'} + +expectTypeOf(getResponsiveProp(cssProperties)) + .exclude() + .exclude<{xs?: unknown}>() + .toEqualTypeOf() + +expectTypeOf(getResponsiveProp(cssProperties)) + .extract() + .toEqualTypeOf() + +expectTypeOf(getResponsiveProp(cssProperties)) + .extract<{xs?: any}>() + .toEqualTypeOf<{xs?: CSSProperties; sm?: CSSProperties; md?: CSSProperties}>() + +expectTypeOf>().exclude().toHaveProperty('sm') +expectTypeOf>().exclude().not.toHaveProperty('xxl') +``` + +`.extract` and `.exclude` return never if no types remain after exclusion: + +```typescript +type Person = {name: string; age: number} +type Customer = Person & {customerId: string} +type Employee = Person & {employeeId: string} + +expectTypeOf().extract<{foo: string}>().toBeNever() +expectTypeOf().exclude<{name: string}>().toBeNever() +``` + +Use `.pick` to pick a set of properties from an object: + +```typescript +type Person = {name: string; age: number} + +expectTypeOf().pick<'name'>().toEqualTypeOf<{name: string}>() +``` + +Use `.omit` to remove a set of properties from an object: + +```typescript +type Person = {name: string; age: number} + +expectTypeOf().omit<'name'>().toEqualTypeOf<{age: number}>() +``` + +Make assertions about object properties: + +```typescript +const obj = {a: 1, b: ''} + +// check that properties exist (or don't) with `.toHaveProperty` +expectTypeOf(obj).toHaveProperty('a') +expectTypeOf(obj).not.toHaveProperty('c') + +// check types of properties +expectTypeOf(obj).toHaveProperty('a').toBeNumber() +expectTypeOf(obj).toHaveProperty('b').toBeString() +expectTypeOf(obj).toHaveProperty('a').not.toBeString() +``` + +`.toEqualTypeOf` can be used to distinguish between functions: + +```typescript +type NoParam = () => void +type HasParam = (s: string) => void + +expectTypeOf().not.toEqualTypeOf() +``` + +But often it's preferable to use `.parameters` or `.returns` for more specific function assertions: + +```typescript +type NoParam = () => void +type HasParam = (s: string) => void + +expectTypeOf().parameters.toEqualTypeOf<[]>() +expectTypeOf().returns.toBeVoid() + +expectTypeOf().parameters.toEqualTypeOf<[string]>() +expectTypeOf().returns.toBeVoid() +``` + +Up to ten overloads will produce union types for `.parameters` and `.returns`: + +```typescript +type Factorize = { + (input: number): number[] + (input: bigint): bigint[] +} + +expectTypeOf().parameters.not.toEqualTypeOf<[number]>() +expectTypeOf().parameters.toEqualTypeOf<[number] | [bigint]>() +expectTypeOf().returns.toEqualTypeOf() + +expectTypeOf().parameter(0).toEqualTypeOf() +``` + +Note that these aren't exactly like TypeScript's built-in Parameters<...> and ReturnType<...>: + +The TypeScript builtins simply choose a single overload (see the [Overloaded functions](#overloaded-functions) section for more information) + +```typescript +type Factorize = { + (input: number): number[] + (input: bigint): bigint[] +} + +// overload using `number` is ignored! +expectTypeOf>().toEqualTypeOf<[bigint]>() +expectTypeOf>().toEqualTypeOf() +``` + +More examples of ways to work with functions - parameters using `.parameter(n)` or `.parameters`, and return values using `.returns`: + +```typescript +const f = (a: number) => [a, a] + +expectTypeOf(f).toBeFunction() + +expectTypeOf(f).toBeCallableWith(1) +expectTypeOf(f).not.toBeAny() +expectTypeOf(f).returns.not.toBeAny() +expectTypeOf(f).returns.toEqualTypeOf([1, 2]) +expectTypeOf(f).returns.toEqualTypeOf([1, 2, 3]) +expectTypeOf(f).parameter(0).not.toEqualTypeOf('1') +expectTypeOf(f).parameter(0).toEqualTypeOf(1) +expectTypeOf(1).parameter(0).toBeNever() + +const twoArgFunc = (a: number, b: string) => ({a, b}) + +expectTypeOf(twoArgFunc).parameters.toEqualTypeOf<[number, string]>() +``` + +`.toBeCallableWith` allows for overloads. You can also use it to narrow down the return type for given input parameters.: + +```typescript +type Factorize = { + (input: number): number[] + (input: bigint): bigint[] +} + +expectTypeOf().toBeCallableWith(6) +expectTypeOf().toBeCallableWith(6n) +``` + +`.toBeCallableWith` returns a type that can be used to narrow down the return type for given input parameters.: + +```typescript +type Factorize = { + (input: number): number[] + (input: bigint): bigint[] +} +expectTypeOf().toBeCallableWith(6).returns.toEqualTypeOf() +expectTypeOf().toBeCallableWith(6n).returns.toEqualTypeOf() +``` + +`.toBeCallableWith` can be used to narrow down the parameters of a function: + +```typescript +type Delete = { + (path: string): void + (paths: string[], options?: {force: boolean}): void +} + +expectTypeOf().toBeCallableWith('abc').parameters.toEqualTypeOf<[string]>() +expectTypeOf() + .toBeCallableWith(['abc', 'def'], {force: true}) + .parameters.toEqualTypeOf<[string[], {force: boolean}?]>() + +expectTypeOf().toBeCallableWith('abc').parameter(0).toBeString() +expectTypeOf().toBeCallableWith('abc').parameter(1).toBeUndefined() + +expectTypeOf() + .toBeCallableWith(['abc', 'def', 'ghi']) + .parameter(0) + .toEqualTypeOf() + +expectTypeOf() + .toBeCallableWith(['abc', 'def', 'ghi']) + .parameter(1) + .toEqualTypeOf<{force: boolean} | undefined>() +``` + +You can't use `.toBeCallableWith` with `.not` - you need to use ts-expect-error:: + +```typescript +const f = (a: number) => [a, a] + +// @ts-expect-error +expectTypeOf(f).toBeCallableWith('foo') +``` + +Use `.map` to transform types: + +This can be useful for generic functions or complex types which you can't access via `.toBeCallableWith`, `.toHaveProperty` etc. The callback function isn't called at runtime, which can make this a useful way to get complex inferred types without worrying about running code. + +```typescript +const capitalize = (input: S) => + (input.slice(0, 1).toUpperCase() + input.slice(1)) as Capitalize + +expectTypeOf(capitalize) + .map(fn => fn('hello world')) + .toEqualTypeOf<'Hello world'>() +``` + +You can also check type guards & type assertions: + +```typescript +const assertNumber = (v: any): asserts v is number => { + if (typeof v !== 'number') { + throw new TypeError('Nope !') + } +} + +expectTypeOf(assertNumber).asserts.toBeNumber() + +const isString = (v: any): v is string => typeof v === 'string' + +expectTypeOf(isString).guards.toBeString() + +const isBigInt = (value: any): value is bigint => typeof value === 'bigint' + +expectTypeOf(isBigInt).guards.toBeBigInt() +``` + +Assert on constructor parameters: + +```typescript +expectTypeOf(Date).toBeConstructibleWith('1970') +expectTypeOf(Date).toBeConstructibleWith(0) +expectTypeOf(Date).toBeConstructibleWith(new Date()) +expectTypeOf(Date).toBeConstructibleWith() + +expectTypeOf(Date).constructorParameters.toEqualTypeOf< + | [] + | [value: string | number] + | [value: string | number | Date] + | [ + year: number, + monthIndex: number, + date?: number | undefined, + hours?: number | undefined, + minutes?: number | undefined, + seconds?: number | undefined, + ms?: number | undefined, + ] +>() +``` + +Constructor overloads: + +```typescript +class DBConnection { + constructor() + constructor(connectionString: string) + constructor(options: {host: string; port: number}) + constructor(..._: unknown[]) {} +} + +expectTypeOf(DBConnection).toBeConstructibleWith() +expectTypeOf(DBConnection).toBeConstructibleWith('localhost') +expectTypeOf(DBConnection).toBeConstructibleWith({host: 'localhost', port: 1234}) +// @ts-expect-error - as when calling `new DBConnection(...)` you can't actually use the `(...args: unknown[])` overlaod, it's purely for the implementation. +expectTypeOf(DBConnection).toBeConstructibleWith(1, 2) +``` + +Check function `this` parameters: + +```typescript +function greet(this: {name: string}, message: string) { + return `Hello ${this.name}, here's your message: ${message}` +} + +expectTypeOf(greet).thisParameter.toEqualTypeOf<{name: string}>() +``` + +Distinguish between functions with different `this` parameters: + +```typescript +function greetFormal(this: {title: string; name: string}, message: string) { + return `Dear ${this.title} ${this.name}, here's your message: ${message}` +} + +function greetCasual(this: {name: string}, message: string) { + return `Hi ${this.name}, here's your message: ${message}` +} + +expectTypeOf(greetFormal).not.toEqualTypeOf(greetCasual) +``` + +Class instance types: + +```typescript +expectTypeOf(Date).instance.toHaveProperty('toISOString') +``` + +Promise resolution types can be checked with `.resolves`: + +```typescript +const asyncFunc = async () => 123 + +expectTypeOf(asyncFunc).returns.resolves.toBeNumber() +``` + +Array items can be checked with `.items`: + +```typescript +expectTypeOf([1, 2, 3]).items.toBeNumber() +expectTypeOf([1, 2, 3]).items.not.toBeString() +``` + +You can also compare arrays directly: + +```typescript +expectTypeOf().not.toEqualTypeOf() +``` + +Check that functions never return: + +```typescript +const thrower = () => { + throw new Error('oh no') +} + +expectTypeOf(thrower).returns.toBeNever() +``` + +Generics can be used rather than references: + +```typescript +expectTypeOf<{a: string}>().not.toEqualTypeOf<{a: number}>() +``` + +Distinguish between missing/null/optional properties: + +```typescript +expectTypeOf<{a?: number}>().not.toEqualTypeOf<{}>() +expectTypeOf<{a?: number}>().not.toEqualTypeOf<{a: number}>() +expectTypeOf<{a?: number}>().not.toEqualTypeOf<{a: number | undefined}>() +expectTypeOf<{a?: number | null}>().not.toEqualTypeOf<{a: number | null}>() +expectTypeOf<{a: {b?: number}}>().not.toEqualTypeOf<{a: {}}>() +``` + +Detect the difference between regular and `readonly` properties: + +```typescript +type A1 = {readonly a: string; b: string} +type E1 = {a: string; b: string} + +expectTypeOf().toExtend() +expectTypeOf().not.toEqualTypeOf() + +type A2 = {a: string; b: {readonly c: string}} +type E2 = {a: string; b: {c: string}} + +expectTypeOf().toExtend() +expectTypeOf().not.toEqualTypeOf() +``` + +Distinguish between classes with different constructors: + +```typescript +class A { + value: number + constructor(a: 1) { + this.value = a + } +} +class B { + value: number + constructor(b: 2) { + this.value = b + } +} + +expectTypeOf().not.toEqualTypeOf() + +class C { + value: number + constructor(c: 1) { + this.value = c + } +} + +expectTypeOf().toEqualTypeOf() +``` + +Known limitation: Intersection types can cause issues with `toEqualTypeOf`: + +```typescript +// @ts-expect-error the following line doesn't compile, even though the types are arguably the same. +// See https://github.com/mmkal/expect-type/pull/21 +expectTypeOf<{a: 1} & {b: 2}>().toEqualTypeOf<{a: 1; b: 2}>() +``` + +To workaround for simple cases, you can use a mapped type: + +```typescript +type Simplify = {[K in keyof T]: T[K]} + +expectTypeOf>().toEqualTypeOf<{a: 1; b: 2}>() +``` + +But this won't work if the nesting is deeper in the type. For these situations, you can use the `.branded` helper. Note that this comes at a performance cost, and can cause the compiler to 'give up' if used with excessively deep types, so use sparingly. This helper is under `.branded` because it deeply transforms the Actual and Expected types into a pseudo-AST: + +```typescript +// @ts-expect-error +expectTypeOf<{a: {b: 1} & {c: 1}}>().toEqualTypeOf<{a: {b: 1; c: 1}}>() + +expectTypeOf<{a: {b: 1} & {c: 1}}>().branded.toEqualTypeOf<{a: {b: 1; c: 1}}>() +``` + +Be careful with `.branded` for very deep or complex types, though. If possible you should find a way to simplify your test to avoid needing to use it: + +```typescript +// This *should* result in an error, but the "branding" mechanism produces too large a type and TypeScript just gives up! https://github.com/microsoft/TypeScript/issues/50670 +expectTypeOf<() => () => () => () => 1>().branded.toEqualTypeOf<() => () => () => () => 2>() + +// @ts-expect-error the non-branded implementation catches the error as expected. +expectTypeOf<() => () => () => () => 1>().toEqualTypeOf<() => () => () => () => 2>() +``` + +So, if you have an extremely deep type that ALSO has an intersection in it, you're out of luck and this library won't be able to test your type properly: + +```typescript +// @ts-expect-error this fails, but it should succeed. +expectTypeOf<() => () => () => () => {a: 1} & {b: 2}>().toEqualTypeOf< + () => () => () => () => {a: 1; b: 2} +>() + +// this succeeds, but it should fail. +expectTypeOf<() => () => () => () => {a: 1} & {b: 2}>().branded.toEqualTypeOf< + () => () => () => () => {a: 1; c: 2} +>() +``` + +Another limitation: passing `this` references to `expectTypeOf` results in errors.: + +```typescript +class B { + b = 'b' + + foo() { + // @ts-expect-error + expectTypeOf(this).toEqualTypeOf(this) + } +} + +// Instead of the above, try something like this: +expectTypeOf(B).instance.toEqualTypeOf<{b: string; foo: () => void}>() +``` + + +Overloads limitation for TypeScript <5.3: Due to a [TypeScript bug fixed in 5.3](https://github.com/microsoft/TypeScript/issues/28867), overloaded functions which include an overload resembling `(...args: unknown[]) => unknown` will exclude `unknown[]` from `.parameters` and exclude `unknown` from `.returns`: + +```typescript +type Factorize = { + (...args: unknown[]): unknown + (input: number): number[] + (input: bigint): bigint[] +} + +expectTypeOf().parameters.toEqualTypeOf<[number] | [bigint]>() +expectTypeOf().returns.toEqualTypeOf() +``` + +This overload, however, allows any input and returns an unknown output anyway, so it's not very useful. If you are worried about this for some reason, you'll have to update TypeScript to 5.3+. + +### Why is my assertion failing? + +For complex types, an assertion might fail when it should if the `Actual` type contains a deeply-nested intersection type but the `Expected` doesn't. In these cases you can use `.branded` as described above: + +```typescript +// @ts-expect-error this unfortunately fails - a TypeScript limitation prevents making this pass without a big perf hit +expectTypeOf<{a: {b: 1} & {c: 1}}>().toEqualTypeOf<{a: {b: 1; c: 1}}>() + +expectTypeOf<{a: {b: 1} & {c: 1}}>().branded.toEqualTypeOf<{a: {b: 1; c: 1}}>() +``` + +### Why is `.toMatchTypeOf` deprecated? + +The `.toMatchTypeOf` method is deprecated in favour of `.toMatchObjectType` (when strictly checking against an object type with a subset of keys), or `.toExtend` (when checking for "is-a" relationships). There are no foreseeable plans to remove `.toMatchTypeOf`, but there's no reason to continue using it - `.toMatchObjectType` is stricter, and `.toExtend` is identical. + +### Internal type helpers + +🚧 This library also exports some helper types for performing boolean operations on types, checking extension/equality in various ways, branding types, and checking for various special types like `never`, `any`, `unknown`. Use at your own risk! Nothing is stopping you from using these beyond this warning: + +>All internal types that are not documented here are _not_ part of the supported API surface, and may be renamed, modified, or removed, without warning or documentation in release notes. + +For a dedicated internal type library, feel free to look at the [source code](./src/index.ts) for inspiration - or better, use a library like [type-fest](https://npmjs.com/package/type-fest). + +### Error messages + +When types don't match, `.toEqualTypeOf` and `.toMatchTypeOf` use a special helper type to produce error messages that are as actionable as possible. But there's a bit of a nuance to understanding them. Since the assertions are written "fluently", the failure should be on the "expected" type, not the "actual" type (`expect().toEqualTypeOf()`). This means that type errors can be a little confusing - so this library produces a `MismatchInfo` type to try to make explicit what the expectation is. For example: + +```ts +expectTypeOf({a: 1}).toEqualTypeOf<{a: string}>() +``` + +Is an assertion that will fail, since `{a: 1}` has type `{a: number}` and not `{a: string}`. The error message in this case will read something like this: + +``` +test/test.ts:999:999 - error TS2344: Type '{ a: string; }' does not satisfy the constraint '{ a: \\"Expected: string, Actual: number\\"; }'. + Types of property 'a' are incompatible. + Type 'string' is not assignable to type '\\"Expected: string, Actual: number\\"'. + +999 expectTypeOf({a: 1}).toEqualTypeOf<{a: string}>() +``` + +Note that the type constraint reported is a human-readable messaging specifying both the "expected" and "actual" types. Rather than taking the sentence `Types of property 'a' are incompatible // Type 'string' is not assignable to type "Expected: string, Actual: number"` literally - just look at the property name (`'a'`) and the message: `Expected: string, Actual: number`. This will tell you what's wrong, in most cases. Extremely complex types will, of course, be more effort to debug, and may require some experimentation. Please [raise an issue](https://github.com/mmkal/expect-type) if the error messages are misleading. + +The `toBe...` methods (like `toBeString`, `toBeNumber`, `toBeVoid`, etc.) fail by resolving to a non-callable type when the `Actual` type under test doesn't match up. For example, the failure for an assertion like `expectTypeOf(1).toBeString()` will look something like this: + +``` +test/test.ts:999:999 - error TS2349: This expression is not callable. + Type 'ExpectString' has no call signatures. + +999 expectTypeOf(1).toBeString() + ~~~~~~~~~~ +``` + +The `This expression is not callable` part isn't all that helpful - the meaningful error is the next line, `Type 'ExpectString has no call signatures`. This essentially means you passed a number but asserted it should be a string. + +If TypeScript added support for ["throw" types](https://github.com/microsoft/TypeScript/pull/40468) these error messages could be improved. Until then they will take a certain amount of squinting. + +#### Concrete "expected" objects vs type arguments + +Error messages for an assertion like this: + +```ts +expectTypeOf({a: 1}).toEqualTypeOf({a: ''}) +``` + +Will be less helpful than for an assertion like this: + +```ts +expectTypeOf({a: 1}).toEqualTypeOf<{a: string}>() +``` + +This is because the TypeScript compiler needs to infer the type argument for the `.toEqualTypeOf({a: ''})` style and this library can only mark it as a failure by comparing it against a generic `Mismatch` type. So, where possible, use a type argument rather than a concrete type for `.toEqualTypeOf` and `toMatchTypeOf`. If it's much more convenient to compare two concrete types, you can use `typeof`: + +```ts +const one = valueFromFunctionOne({some: {complex: inputs}}) +const two = valueFromFunctionTwo({some: {other: inputs}}) + +expectTypeOf(one).toEqualTypeof() +``` + +### Overloaded functions + +Due to a TypeScript [design limitation](https://github.com/microsoft/TypeScript/issues/32164#issuecomment-506810756), the native TypeScript `Parameters<...>` and `ReturnType<...>` helpers only return types from one variant of an overloaded function. This limitation doesn't apply to expect-type, since it is not used to author TypeScript code, only to assert on existing types. So, we use a workaround for this TypeScript behaviour to assert on _all_ overloads as a union (actually, not necessarily _all_ - we cap out at 10 overloads). + +### Within test frameworks + +### Vitest + +`expectTypeOf` is built in to [vitest](https://vitest.dev/guide/testing-types), so you can import `expectTypeOf` from the vitest library directly if you prefer. Note that there is no set release cadence, at time of writing, so vitest may not always be using the very latest version. + +```ts +import {expectTypeOf} from 'vitest' +import {mount} from './mount.js' + +test('my types work properly', () => { + expectTypeOf(mount).toBeFunction() + expectTypeOf(mount).parameter(0).toEqualTypeOf<{name: string}>() + + expectTypeOf(mount({name: 42})).toBeString() +}) +``` + +#### Jest & `eslint-plugin-jest` + +If you're using Jest along with `eslint-plugin-jest`, and you put assertions inside `test(...)` definitions, you may get warnings from the [`jest/expect-expect`](https://github.com/jest-community/eslint-plugin-jest/blob/master/docs/rules/expect-expect.md) rule, complaining that "Test has no assertions" for tests that only use `expectTypeOf()`. + +To remove this warning, configure the ESLint rule to consider `expectTypeOf` as an assertion: + +```json +"rules": { + // ... + "jest/expect-expect": [ + "warn", + { + "assertFunctionNames": [ + "expect", "expectTypeOf" + ] + } + ], + // ... +} +``` + +### Limitations + +A summary of some of the limitations of this library. Some of these are documented more fully elsewhere. + +1. Intersection types can result in failures when the expected and actual types are not identically defined, even when they are effectively identical. See [Why is my assertion failing](#why-is-my-assertion-failing) for details. TL;DR: use `.brand` in these cases - and accept the performance hit that it comes with. +1. `toBeCallableWith` will likely fail if you try to use it with a generic function or an overload. See [this issue](https://github.com/mmkal/expect-type/issues/50) for an example and how to work around it. +1. (For now) overloaded functions might trip up the `.parameter` and `.parameters` helpers. This matches how the built-in TypeScript helper `Parameters<...>` works. This may be improved in the future though ([see related issue](https://github.com/mmkal/expect-type/issues/30)). +1. `expectTypeOf(this).toEqualTypeOf(this)` inside class methods does not work. + +## Similar projects + +Other projects with similar goals: + +- [`tsd`](https://github.com/SamVerschueren/tsd) is a CLI that runs the TypeScript type checker over assertions +- [`ts-expect`](https://github.com/TypeStrong/ts-expect) exports several generic helper types to perform type assertions +- [`dtslint`](https://github.com/Microsoft/dtslint) does type checks via comment directives and tslint +- [`type-plus`](https://github.com/unional/type-plus) comes with various type and runtime TypeScript assertions +- [`static-type-assert`](https://github.com/ksxnodemodules/static-type-assert) type assertion functions + +### Comparison + +The key differences in this project are: + +- a fluent, jest-inspired API, making the difference between `actual` and `expected` clear. This is helpful with complex types and assertions. +- inverting assertions intuitively and easily via `expectTypeOf(...).not` +- checks generics properly and strictly ([tsd doesn't](https://github.com/SamVerschueren/tsd/issues/142)) +- first-class support for: + - `any` (as well as `unknown` and `never`) (see issues outstanding at time of writing in tsd for [never](https://github.com/SamVerschueren/tsd/issues/78) and [any](https://github.com/SamVerschueren/tsd/issues/82)). + - This can be especially useful in combination with `not`, to protect against functions returning too-permissive types. For example, `const parseFile = (filename: string) => JSON.parse(readFileSync(filename).toString())` returns `any`, which could lead to errors. After giving it a proper return-type, you can add a test for this with `expect(parseFile).returns.not.toBeAny()` + - object properties + - function parameters + - function return values + - constructor parameters + - class instances + - array item values + - nullable types +- assertions on types "matching" rather than exact type equality, for "is-a" relationships e.g. `expectTypeOf(square).toExtend()` +- built into existing tooling. No extra build step, cli tool, IDE extension, or lint plugin is needed. Just import the function and start writing tests. Failures will be at compile time - they'll appear in your IDE and when you run `tsc`. +- small implementation with no dependencies. [Take a look!](./src/index.ts) (tsd, for comparison, is [2.6MB](https://bundlephobia.com/result?p=tsd@0.13.1) because it ships a patched version of TypeScript). + +## TypeScript backwards-compatibility + +There is a CI job called `test-types` that checks whether the tests still pass with certain older TypeScript versions. To check the supported TypeScript versions, [refer to the job definition](./.github/workflows/ci.yml). + +## Contributing + +In most cases, it's worth checking existing issues or creating one to discuss a new feature or a bug fix before opening a pull request. + +Once you're ready to make a pull request: clone the repo, and install pnpm if you don't have it already with `npm install --global pnpm`. Lockfiles for `npm` and `yarn` are gitignored. + +If you're adding a feature, you should write a self-contained usage example in the form of a test, in [test/usage.test.ts](./test/usage.test.ts). This file is used to populate the bulk of this readme using [eslint-plugin-codegen](https://npmjs.com/package/eslint-plugin-codegen), and to generate an ["errors" test file](./test/errors.test.ts), which captures the error messages that are emitted for failing assertions by the TypeScript compiler. So, the test name should be written as a human-readable sentence explaining the usage example. Have a look at the existing tests for an idea of the style. + +After adding the tests, run `npm run lint -- --fix` to update the readme, and `npm test -- --updateSnapshot` to update the errors test. The generated documentation and tests should be pushed to the same branch as the source code, and submitted as a pull request. CI will test that the docs and tests are up to date if you forget to run these commands. + +### Documentation of limitations through tests + +Limitations of the library are documented through tests in `usage.test.ts`. This means that if a future TypeScript version (or library version) fixes the limitation, the test will start failing, and it will be automatically removed from the documentation once it no longer applies. diff --git a/node_modules/expect-type/SECURITY.md b/node_modules/expect-type/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..3f988a6f4ff2fdbe5f1810e957155432f2499d63 --- /dev/null +++ b/node_modules/expect-type/SECURITY.md @@ -0,0 +1,14 @@ +# Security Policy + +## Supported Versions + +Version 1.0.0 will be supported with security updates. + +| Version | Supported | +| ------- | ------------------ | +| 1.x.x | :white_check_mark: | +| < 1.0 | :x: | + +## Reporting a Vulnerability + +To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. diff --git a/node_modules/expect-type/dist/branding.d.ts b/node_modules/expect-type/dist/branding.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b59cccd15984ad17df7f63722e47ecf3ade78817 --- /dev/null +++ b/node_modules/expect-type/dist/branding.d.ts @@ -0,0 +1,61 @@ +import type { ConstructorOverloadParameters, NumOverloads, OverloadsInfoUnion } from './overloads'; +import type { IsNever, IsAny, IsUnknown, ReadonlyKeys, RequiredKeys, OptionalKeys, MutuallyExtends, UnionToTuple } from './utils'; +/** + * Represents a deeply branded type. + * + * Recursively walk a type and replace it with a branded type related to the + * original. This is useful for equality-checking stricter than + * `A extends B ? B extends A ? true : false : false`, because it detects the + * difference between a few edge-case types that vanilla TypeScript + * doesn't by default: + * - `any` vs `unknown` + * - `{ readonly a: string }` vs `{ a: string }` + * - `{ a?: string }` vs `{ a: string | undefined }` + * + * __Note__: not very performant for complex types - this should only be used + * when you know you need it. If doing an equality check, it's almost always + * better to use {@linkcode StrictEqualUsingTSInternalIdenticalToOperator}. + */ +export type DeepBrand = IsNever extends true ? { + type: 'never'; +} : IsAny extends true ? { + type: 'any'; +} : IsUnknown extends true ? { + type: 'unknown'; +} : T extends string | number | boolean | symbol | bigint | null | undefined | void ? { + type: 'primitive'; + value: T; +} : T extends new (...args: any[]) => any ? { + type: 'constructor'; + params: ConstructorOverloadParameters; + instance: DeepBrand any>>>; +} : T extends (...args: infer P) => infer R ? NumOverloads extends 1 ? { + type: 'function'; + params: DeepBrand

; + return: DeepBrand; + this: DeepBrand>; + props: DeepBrand>; +} : UnionToTuple> extends infer OverloadsTuple ? { + type: 'overloads'; + overloads: { + [K in keyof OverloadsTuple]: DeepBrand; + }; +} : never : T extends any[] ? { + type: 'array'; + items: { + [K in keyof T]: T[K]; + }; +} : { + type: 'object'; + properties: { + [K in keyof T]: DeepBrand; + }; + readonly: ReadonlyKeys; + required: RequiredKeys; + optional: OptionalKeys; + constructorParams: DeepBrand>; +}; +/** + * Checks if two types are strictly equal using branding. + */ +export type StrictEqualUsingBranding = MutuallyExtends, DeepBrand>; diff --git a/node_modules/expect-type/dist/branding.js b/node_modules/expect-type/dist/branding.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/expect-type/dist/branding.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/expect-type/dist/index.d.ts b/node_modules/expect-type/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4098988f1a007125653df917aad8231925d63f8a --- /dev/null +++ b/node_modules/expect-type/dist/index.d.ts @@ -0,0 +1,897 @@ +import type { StrictEqualUsingBranding } from './branding'; +import type { ExpectAny, ExpectArray, ExpectBigInt, ExpectBoolean, ExpectFunction, ExpectNever, ExpectNull, ExpectNullable, ExpectNumber, ExpectObject, ExpectString, ExpectSymbol, ExpectUndefined, ExpectUnknown, ExpectVoid, MismatchInfo, Scolder } from './messages'; +import type { ConstructorOverloadParameters, OverloadParameters, OverloadReturnTypes, OverloadsNarrowedByParameters } from './overloads'; +import type { AValue, DeepPickMatchingProps, Extends, IsUnion, MismatchArgs, Not, StrictEqualUsingTSInternalIdenticalToOperator } from './utils'; +export * from './branding'; +export * from './messages'; +export * from './overloads'; +export * from './utils'; +/** + * Represents the positive assertion methods available for type checking in the + * {@linkcode expectTypeOf()} utility. + */ +export interface PositiveExpectTypeOf extends BaseExpectTypeOf { + /** + * Similar to jest's `expect(...).toMatchObject(...)` but for types. + * Deeply "picks" the properties of the actual type based on the expected type, then performs a strict check to make sure the types match `Expected`. + * + * **Note**: optional properties on the {@linkcode Expected | expected type} are not allowed to be missing on the {@linkcode Actual | actual type}. + * + * @example + * ```ts + * expectTypeOf({ a: 1, b: 1 }).toMatchObjectType<{ a: number }>() + * + * expectTypeOf({ a: 1, b: 1 }).not.toMatchObjectType<{ a: number; c?: number }>() + * ``` + * + * @param MISMATCH - The mismatch arguments. + * @returns `true`. + */ + toMatchObjectType: extends true ? 'toMatchObject does not support union types' : Not>> extends true ? 'toMatchObject only supports object types' : StrictEqualUsingTSInternalIdenticalToOperator, Expected> extends true ? unknown : MismatchInfo, Expected>>(...MISMATCH: MismatchArgs, Expected>, true>) => true; + /** + * Check if your type extends the expected type + * + * A less strict version of {@linkcode toEqualTypeOf | .toEqualTypeOf()} that allows for extra properties. + * This is roughly equivalent to an `extends` constraint in a function type argument. + * + * @example + * ```ts + * expectTypeOf({ a: 1, b: 1 }).toExtend<{ a: number }>() + * + * expectTypeOf({ a: 1 }).not.toExtend<{ b: number }>() + * ``` + * + * @param MISMATCH - The mismatch arguments. + * @returns `true`. + */ + toExtend: extends true ? unknown : MismatchInfo>(...MISMATCH: MismatchArgs, true>) => true; + toEqualTypeOf: { + /** + * Uses TypeScript's internal technique to check for type "identicalness". + * + * It will check if the types are fully equal to each other. + * It will not fail if two objects have different values, but the same type. + * It will fail however if an object is missing a property. + * + * **_Unexpected failure_**? For a more permissive but less performant + * check that accommodates for equivalent intersection types, + * use {@linkcode branded | .branded.toEqualTypeOf()}. + * @see {@link https://github.com/mmkal/expect-type#why-is-my-assertion-failing | The documentation for details}. + * + * @example + * Using generic type argument syntax + * ```ts + * expectTypeOf({ a: 1 }).toEqualTypeOf<{ a: number }>() + * + * expectTypeOf({ a: 1, b: 1 }).not.toEqualTypeOf<{ a: number }>() + * ``` + * + * @example + * Using inferred type syntax by passing a value + * ```ts + * expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 1 }) + * + * expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 2 }) + * ``` + * + * @param value - The value to compare against the expected type. + * @param MISMATCH - The mismatch arguments. + * @returns `true`. + */ + extends true ? unknown : MismatchInfo>(value: Expected & AValue, // reason for `& AValue`: make sure this is only the selected overload when the end-user passes a value for an inferred typearg. The `Mismatch` type does match `AValue`. + ...MISMATCH: MismatchArgs, true>): true; + /** + * Uses TypeScript's internal technique to check for type "identicalness". + * + * It will check if the types are fully equal to each other. + * It will not fail if two objects have different values, but the same type. + * It will fail however if an object is missing a property. + * + * **_Unexpected failure_**? For a more permissive but less performant + * check that accommodates for equivalent intersection types, + * use {@linkcode branded | .branded.toEqualTypeOf()}. + * @see {@link https://github.com/mmkal/expect-type#why-is-my-assertion-failing | The documentation for details}. + * + * @example + * Using generic type argument syntax + * ```ts + * expectTypeOf({ a: 1 }).toEqualTypeOf<{ a: number }>() + * + * expectTypeOf({ a: 1, b: 1 }).not.toEqualTypeOf<{ a: number }>() + * ``` + * + * @example + * Using inferred type syntax by passing a value + * ```ts + * expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 1 }) + * + * expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 2 }) + * ``` + * + * @param MISMATCH - The mismatch arguments. + * @returns `true`. + */ + extends true ? unknown : MismatchInfo>(...MISMATCH: MismatchArgs, true>): true; + }; + /** + * @deprecated Since v1.2.0 - Use either {@linkcode toMatchObjectType} or {@linkcode toExtend} instead + * + * - Use {@linkcode toMatchObjectType} to perform a strict check on a subset of your type's keys + * - Use {@linkcode toExtend} to check if your type extends the expected type + */ + toMatchTypeOf: { + /** + * @deprecated Since v1.2.0 - Use either {@linkcode toMatchObjectType} or {@linkcode toExtend} instead + * + * - Use {@linkcode toMatchObjectType} to perform a strict check on a subset of your type's keys + * - Use {@linkcode toExtend} to check if your type extends the expected type + * + * A less strict version of {@linkcode toEqualTypeOf | .toEqualTypeOf()} + * that allows for extra properties. + * This is roughly equivalent to an `extends` constraint + * in a function type argument. + * + * @example + * Using generic type argument syntax + * ```ts + * expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf<{ a: number }>() + * ``` + * + * @example + * Using inferred type syntax by passing a value + * ```ts + * expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf({ a: 2 }) + * ``` + * + * @param value - The value to compare against the expected type. + * @param MISMATCH - The mismatch arguments. + * @returns `true`. + */ + extends true ? unknown : MismatchInfo>(value: Expected & AValue, // reason for `& AValue`: make sure this is only the selected overload when the end-user passes a value for an inferred typearg. The `Mismatch` type does match `AValue`. + ...MISMATCH: MismatchArgs, true>): true; + /** + * @deprecated Since v1.2.0 - Use either {@linkcode toMatchObjectType} or {@linkcode toExtend} instead + * + * - Use {@linkcode toMatchObjectType} to perform a strict check on a subset of your type's keys + * - Use {@linkcode toExtend} to check if your type extends the expected type + * + * A less strict version of {@linkcode toEqualTypeOf | .toEqualTypeOf()} + * that allows for extra properties. + * This is roughly equivalent to an `extends` constraint + * in a function type argument. + * + * @example + * Using generic type argument syntax + * ```ts + * expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf<{ a: number }>() + * ``` + * + * @example + * Using inferred type syntax by passing a value + * ```ts + * expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf({ a: 2 }) + * ``` + * + * @param MISMATCH - The mismatch arguments. + * @returns `true`. + */ + extends true ? unknown : MismatchInfo>(...MISMATCH: MismatchArgs, true>): true; + }; + /** + * Checks whether an object has a given property. + * + * @example + * check that properties exist + * ```ts + * const obj = { a: 1, b: '' } + * + * expectTypeOf(obj).toHaveProperty('a') + * + * expectTypeOf(obj).not.toHaveProperty('c') + * ``` + * + * @param key - The property key to check for. + * @param MISMATCH - The mismatch arguments. + * @returns `true`. + */ + toHaveProperty: (key: KeyType, ...MISMATCH: MismatchArgs, true>) => KeyType extends keyof Actual ? PositiveExpectTypeOf : true; + /** + * Inverts the result of the following assertions. + * + * @example + * ```ts + * expectTypeOf({ a: 1 }).not.toMatchTypeOf({ b: 1 }) + * ``` + */ + not: NegativeExpectTypeOf; + /** + * Intersection types can cause issues with + * {@linkcode toEqualTypeOf | .toEqualTypeOf()}: + * ```ts + * // ❌ The following line doesn't compile, even though the types are arguably the same. + * expectTypeOf<{ a: 1 } & { b: 2 }>().toEqualTypeOf<{ a: 1; b: 2 }>() + * ``` + * This helper works around this problem by using + * a more permissive but less performant check. + * + * __Note__: This comes at a performance cost, and can cause the compiler + * to 'give up' if used with excessively deep types, so use sparingly. + * + * @see {@link https://github.com/mmkal/expect-type/pull/21 | Reference} + */ + branded: { + /** + * Uses TypeScript's internal technique to check for type "identicalness". + * + * It will check if the types are fully equal to each other. + * It will not fail if two objects have different values, but the same type. + * It will fail however if an object is missing a property. + * + * **_Unexpected failure_**? For a more permissive but less performant + * check that accommodates for equivalent intersection types, + * use {@linkcode PositiveExpectTypeOf.branded | .branded.toEqualTypeOf()}. + * @see {@link https://github.com/mmkal/expect-type#why-is-my-assertion-failing | The documentation for details}. + * + * @example + * Using generic type argument syntax + * ```ts + * expectTypeOf({ a: 1 }).toEqualTypeOf<{ a: number }>() + * + * expectTypeOf({ a: 1, b: 1 }).not.toEqualTypeOf<{ a: number }>() + * ``` + * + * @example + * Using inferred type syntax by passing a value + * ```ts + * expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 1 }) + * + * expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 2 }) + * ``` + * + * @param MISMATCH - The mismatch arguments. + * @returns `true`. + */ + toEqualTypeOf: extends true ? unknown : MismatchInfo>(...MISMATCH: MismatchArgs, true>) => true; + }; +} +/** + * Represents the negative expectation type for the {@linkcode Actual} type. + */ +export interface NegativeExpectTypeOf extends BaseExpectTypeOf { + /** + * Similar to jest's `expect(...).toMatchObject(...)` but for types. + * Deeply "picks" the properties of the actual type based on the expected type, then performs a strict check to make sure the types match `Expected`. + * + * **Note**: optional properties on the {@linkcode Expected | expected type} are not allowed to be missing on the {@linkcode Actual | actual type}. + * + * @example + * ```ts + * expectTypeOf({ a: 1, b: 1 }).toMatchObjectType<{ a: number }>() + * + * expectTypeOf({ a: 1, b: 1 }).not.toMatchObjectType<{ a: number; c?: number }>() + * ``` + * + * @param MISMATCH - The mismatch arguments. + * @returns `true`. + */ + toMatchObjectType: (...MISMATCH: MismatchArgs, Expected>, false>) => true; + /** + * Check if your type extends the expected type + * + * A less strict version of {@linkcode PositiveExpectTypeOf.toEqualTypeOf | .toEqualTypeOf()} that allows for extra properties. + * This is roughly equivalent to an `extends` constraint in a function type argument. + * + * @example + * ```ts + * expectTypeOf({ a: 1, b: 1 }).toExtend<{ a: number }>()] + * + * expectTypeOf({ a: 1 }).not.toExtend<{ b: number }>() + * ``` + * + * @param MISMATCH - The mismatch arguments. + * @returns `true`. + */ + toExtend(...MISMATCH: MismatchArgs, false>): true; + toEqualTypeOf: { + /** + * Uses TypeScript's internal technique to check for type "identicalness". + * + * It will check if the types are fully equal to each other. + * It will not fail if two objects have different values, but the same type. + * It will fail however if an object is missing a property. + * + * **_Unexpected failure_**? For a more permissive but less performant + * check that accommodates for equivalent intersection types, + * use {@linkcode PositiveExpectTypeOf.branded | .branded.toEqualTypeOf()}. + * @see {@link https://github.com/mmkal/expect-type#why-is-my-assertion-failing | The documentation for details}. + * + * @example + * Using generic type argument syntax + * ```ts + * expectTypeOf({ a: 1 }).toEqualTypeOf<{ a: number }>() + * + * expectTypeOf({ a: 1, b: 1 }).not.toEqualTypeOf<{ a: number }>() + * ``` + * + * @example + * Using inferred type syntax by passing a value + * ```ts + * expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 1 }) + * + * expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 2 }) + * ``` + * + * @param value - The value to compare against the expected type. + * @param MISMATCH - The mismatch arguments. + * @returns `true`. + */ + (value: Expected & AValue, ...MISMATCH: MismatchArgs, false>): true; + /** + * Uses TypeScript's internal technique to check for type "identicalness". + * + * It will check if the types are fully equal to each other. + * It will not fail if two objects have different values, but the same type. + * It will fail however if an object is missing a property. + * + * **_Unexpected failure_**? For a more permissive but less performant + * check that accommodates for equivalent intersection types, + * use {@linkcode PositiveExpectTypeOf.branded | .branded.toEqualTypeOf()}. + * @see {@link https://github.com/mmkal/expect-type#why-is-my-assertion-failing | The documentation for details}. + * + * @example + * Using generic type argument syntax + * ```ts + * expectTypeOf({ a: 1 }).toEqualTypeOf<{ a: number }>() + * + * expectTypeOf({ a: 1, b: 1 }).not.toEqualTypeOf<{ a: number }>() + * ``` + * + * @example + * Using inferred type syntax by passing a value + * ```ts + * expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 1 }) + * + * expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 2 }) + * ``` + * + * @param MISMATCH - The mismatch arguments. + * @returns `true`. + */ + (...MISMATCH: MismatchArgs, false>): true; + }; + /** + * @deprecated Since v1.2.0 - Use either {@linkcode toMatchObjectType} or {@linkcode toExtend} instead + * + * - Use {@linkcode toMatchObjectType} to perform a strict check on a subset of your type's keys + * - Use {@linkcode toExtend} to check if your type extends the expected type + */ + toMatchTypeOf: { + /** + * @deprecated Since v1.2.0 - Use either {@linkcode toMatchObjectType} or {@linkcode toExtend} instead + * + * - Use {@linkcode toMatchObjectType} to perform a strict check on a subset of your type's keys + * - Use {@linkcode toExtend} to check if your type extends the expected type + * + * A less strict version of + * {@linkcode PositiveExpectTypeOf.toEqualTypeOf | .toEqualTypeOf()} + * that allows for extra properties. + * This is roughly equivalent to an `extends` constraint + * in a function type argument. + * + * @example + * Using generic type argument syntax + * ```ts + * expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf<{ a: number }>() + * ``` + * + * @example + * Using inferred type syntax by passing a value + * ```ts + * expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf({ a: 2 }) + * ``` + * + * @param value - The value to compare against the expected type. + * @param MISMATCH - The mismatch arguments. + * @returns `true`. + */ + (value: Expected & AValue, // reason for `& AValue`: make sure this is only the selected overload when the end-user passes a value for an inferred typearg. The `Mismatch` type does match `AValue`. + ...MISMATCH: MismatchArgs, false>): true; + /** + * @deprecated Since v1.2.0 - Use either {@linkcode toMatchObjectType} or {@linkcode toExtend} instead + * + * - Use {@linkcode toMatchObjectType} to perform a strict check on a subset of your type's keys + * - Use {@linkcode toExtend} to check if your type extends the expected type + * + * A less strict version of + * {@linkcode PositiveExpectTypeOf.toEqualTypeOf | .toEqualTypeOf()} + * that allows for extra properties. + * This is roughly equivalent to an `extends` constraint + * in a function type argument. + * + * @example + * Using generic type argument syntax + * ```ts + * expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf<{ a: number }>() + * ``` + * + * @example + * Using inferred type syntax by passing a value + * ```ts + * expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf({ a: 2 }) + * ``` + * + * @param MISMATCH - The mismatch arguments. + * @returns `true`. + */ + (...MISMATCH: MismatchArgs, false>): true; + }; + /** + * Checks whether an object has a given property. + * + * @example + * check that properties exist + * ```ts + * const obj = { a: 1, b: '' } + * + * expectTypeOf(obj).toHaveProperty('a') + * + * expectTypeOf(obj).not.toHaveProperty('c') + * ``` + * + * @param key - The property key to check for. + * @param MISMATCH - The mismatch arguments. + * @returns `true`. + */ + toHaveProperty: (key: KeyType, ...MISMATCH: MismatchArgs, false>) => true; +} +/** + * Represents a conditional type that selects either + * {@linkcode PositiveExpectTypeOf} or {@linkcode NegativeExpectTypeOf} based + * on the value of the `positive` property in the {@linkcode Options} type. + */ +export type ExpectTypeOf = Options['positive'] extends true ? PositiveExpectTypeOf : NegativeExpectTypeOf; +/** + * Represents the base interface for the + * {@linkcode expectTypeOf()} function. + * Provides a set of assertion methods to perform type checks on a value. + */ +export interface BaseExpectTypeOf { + /** + * Checks whether the type of the value is `any`. + */ + toBeAny: Scolder, Options>; + /** + * Checks whether the type of the value is `unknown`. + */ + toBeUnknown: Scolder, Options>; + /** + * Checks whether the type of the value is `never`. + */ + toBeNever: Scolder, Options>; + /** + * Checks whether the type of the value is `function`. + */ + toBeFunction: Scolder, Options>; + /** + * Checks whether the type of the value is `object`. + */ + toBeObject: Scolder, Options>; + /** + * Checks whether the type of the value is an {@linkcode Array}. + */ + toBeArray: Scolder, Options>; + /** + * Checks whether the type of the value is `number`. + */ + toBeNumber: Scolder, Options>; + /** + * Checks whether the type of the value is `string`. + */ + toBeString: Scolder, Options>; + /** + * Checks whether the type of the value is `boolean`. + */ + toBeBoolean: Scolder, Options>; + /** + * Checks whether the type of the value is `void`. + */ + toBeVoid: Scolder, Options>; + /** + * Checks whether the type of the value is `symbol`. + */ + toBeSymbol: Scolder, Options>; + /** + * Checks whether the type of the value is `null`. + */ + toBeNull: Scolder, Options>; + /** + * Checks whether the type of the value is `undefined`. + */ + toBeUndefined: Scolder, Options>; + /** + * Checks whether the type of the value is `null` or `undefined`. + */ + toBeNullable: Scolder, Options>; + /** + * Transform that type of the value via a callback. + * + * @param fn - A callback that transforms the input value. Note that this function is not actually called - it's only used for type inference. + * @returns A new type which can be used for further assertions. + */ + map: (fn: (value: Actual) => T) => ExpectTypeOf; + /** + * Checks whether the type of the value is **`bigint`**. + * + * @example + * #### Distinguish between **`number`** and **`bigint`** + * + * ```ts + * import { expectTypeOf } from 'expect-type' + * + * const aVeryBigInteger = 10n ** 100n + * + * expectTypeOf(aVeryBigInteger).not.toBeNumber() + * + * expectTypeOf(aVeryBigInteger).toBeBigInt() + * ``` + * + * @since 1.1.0 + */ + toBeBigInt: Scolder, Options>; + /** + * Checks whether a function is callable with the given parameters. + * + * __Note__: You cannot negate this assertion with + * {@linkcode PositiveExpectTypeOf.not | .not}, you need to use + * `ts-expect-error` instead. + * + * @example + * ```ts + * const f = (a: number) => [a, a] + * + * expectTypeOf(f).toBeCallableWith(1) + * ``` + * + * __Known Limitation__: This assertion will likely fail if you try to use it + * with a generic function or an overload. + * @see {@link https://github.com/mmkal/expect-type/issues/50 | This issue} for an example and a workaround. + * + * @param args - The arguments to check for callability. + * @returns `true`. + */ + toBeCallableWith: Options['positive'] extends true ? >(...args: Args) => ExpectTypeOf, Options> : never; + /** + * Checks whether a class is constructible with the given parameters. + * + * @example + * ```ts + * expectTypeOf(Date).toBeConstructibleWith('1970') + * + * expectTypeOf(Date).toBeConstructibleWith(0) + * + * expectTypeOf(Date).toBeConstructibleWith(new Date()) + * + * expectTypeOf(Date).toBeConstructibleWith() + * ``` + * + * @param args - The arguments to check for constructibility. + * @returns `true`. + */ + toBeConstructibleWith: Options['positive'] extends true ? >(...args: Args) => true : never; + /** + * Equivalent to the {@linkcode Extract} utility type. + * Helps narrow down complex union types. + * + * @example + * ```ts + * type ResponsiveProp = T | T[] | { xs?: T; sm?: T; md?: T } + * + * interface CSSProperties { + * margin?: string + * padding?: string + * } + * + * function getResponsiveProp(_props: T): ResponsiveProp { + * return {} + * } + * + * const cssProperties: CSSProperties = { margin: '1px', padding: '2px' } + * + * expectTypeOf(getResponsiveProp(cssProperties)) + * .extract<{ xs?: any }>() // extracts the last type from a union + * .toEqualTypeOf<{ + * xs?: CSSProperties + * sm?: CSSProperties + * md?: CSSProperties + * }>() + * + * expectTypeOf(getResponsiveProp(cssProperties)) + * .extract() // extracts an array from a union + * .toEqualTypeOf() + * ``` + * + * __Note__: If no type is found in the union, it will return `never`. + * + * @param v - The type to extract from the union. + * @returns The type after extracting the type from the union. + */ + extract: (v?: V) => ExpectTypeOf, Options>; + /** + * Equivalent to the {@linkcode Exclude} utility type. + * Removes types from a union. + * + * @example + * ```ts + * type ResponsiveProp = T | T[] | { xs?: T; sm?: T; md?: T } + * + * interface CSSProperties { + * margin?: string + * padding?: string + * } + * + * function getResponsiveProp(_props: T): ResponsiveProp { + * return {} + * } + * + * const cssProperties: CSSProperties = { margin: '1px', padding: '2px' } + * + * expectTypeOf(getResponsiveProp(cssProperties)) + * .exclude() + * .exclude<{ xs?: unknown }>() // or just `.exclude()` + * .toEqualTypeOf() + * ``` + */ + exclude: (v?: V) => ExpectTypeOf, Options>; + /** + * Equivalent to the {@linkcode Pick} utility type. + * Helps select a subset of properties from an object type. + * + * @example + * ```ts + * interface Person { + * name: string + * age: number + * } + * + * expectTypeOf() + * .pick<'name'>() + * .toEqualTypeOf<{ name: string }>() + * ``` + * + * @param keyToPick - The property key to pick. + * @returns The type after picking the property. + */ + pick: (keyToPick?: KeyToPick) => ExpectTypeOf, Options>; + /** + * Equivalent to the {@linkcode Omit} utility type. + * Helps remove a subset of properties from an object type. + * + * @example + * ```ts + * interface Person { + * name: string + * age: number + * } + * + * expectTypeOf().omit<'name'>().toEqualTypeOf<{ age: number }>() + * ``` + * + * @param keyToOmit - The property key to omit. + * @returns The type after omitting the property. + */ + omit: )>(keyToOmit?: KeyToOmit) => ExpectTypeOf, Options>; + /** + * Extracts a certain function argument with `.parameter(number)` call to + * perform other assertions on it. + * + * @example + * ```ts + * function foo(a: number, b: string) { + * return [a, b] + * } + * + * expectTypeOf(foo).parameter(0).toBeNumber() + * + * expectTypeOf(foo).parameter(1).toBeString() + * ``` + * + * @param index - The index of the parameter to extract. + * @returns The extracted parameter type. + */ + parameter: (index: Index) => ExpectTypeOf[Index], Options>; + /** + * Equivalent to the {@linkcode Parameters} utility type. + * Extracts function parameters to perform assertions on its value. + * Parameters are returned as an array. + * + * @example + * ```ts + * function noParam() {} + * + * function hasParam(s: string) {} + * + * expectTypeOf(noParam).parameters.toEqualTypeOf<[]>() + * + * expectTypeOf(hasParam).parameters.toEqualTypeOf<[string]>() + * ``` + */ + parameters: ExpectTypeOf, Options>; + /** + * Equivalent to the {@linkcode ConstructorParameters} utility type. + * Extracts constructor parameters as an array of values and + * perform assertions on them with this method. + * + * For overloaded constructors it will return a union of all possible parameter-tuples. + * + * @example + * ```ts + * expectTypeOf(Date).constructorParameters.toEqualTypeOf< + * [] | [string | number | Date] + * >() + * ``` + */ + constructorParameters: ExpectTypeOf, Options>; + /** + * Equivalent to the {@linkcode ThisParameterType} utility type. + * Extracts the `this` parameter of a function to + * perform assertions on its value. + * + * @example + * ```ts + * function greet(this: { name: string }, message: string) { + * return `Hello ${this.name}, here's your message: ${message}` + * } + * + * expectTypeOf(greet).thisParameter.toEqualTypeOf<{ name: string }>() + * ``` + */ + thisParameter: ExpectTypeOf, Options>; + /** + * Equivalent to the {@linkcode InstanceType} utility type. + * Extracts the instance type of a class to perform assertions on. + * + * @example + * ```ts + * expectTypeOf(Date).instance.toHaveProperty('toISOString') + * ``` + */ + instance: Actual extends new (...args: any[]) => infer I ? ExpectTypeOf : never; + /** + * Equivalent to the {@linkcode ReturnType} utility type. + * Extracts the return type of a function. + * + * @example + * ```ts + * expectTypeOf(() => {}).returns.toBeVoid() + * + * expectTypeOf((a: number) => [a, a]).returns.toEqualTypeOf([1, 2]) + * ``` + */ + returns: Actual extends Function ? ExpectTypeOf, Options> : never; + /** + * Extracts resolved value of a Promise, + * so you can perform other assertions on it. + * + * @example + * ```ts + * async function asyncFunc() { + * return 123 + * } + * + * expectTypeOf(asyncFunc).returns.resolves.toBeNumber() + * + * expectTypeOf(Promise.resolve('string')).resolves.toBeString() + * ``` + * + * Type Equivalent: + * ```ts + * type Resolves = PromiseType extends PromiseLike + * ? ResolvedType + * : never + * ``` + */ + resolves: Actual extends PromiseLike ? ExpectTypeOf : never; + /** + * Extracts array item type to perform assertions on. + * + * @example + * ```ts + * expectTypeOf([1, 2, 3]).items.toEqualTypeOf() + * + * expectTypeOf([1, 2, 3]).items.not.toEqualTypeOf() + * ``` + * + * __Type Equivalent__: + * ```ts + * type Items = ArrayType extends ArrayLike + * ? ItemType + * : never + * ``` + */ + items: Actual extends ArrayLike ? ExpectTypeOf : never; + /** + * Extracts the type guarded by a function to perform assertions on. + * + * @example + * ```ts + * function isString(v: any): v is string { + * return typeof v === 'string' + * } + * + * expectTypeOf(isString).guards.toBeString() + * ``` + */ + guards: Actual extends (v: any, ...args: any[]) => v is infer T ? ExpectTypeOf : never; + /** + * Extracts the type asserted by a function to perform assertions on. + * + * @example + * ```ts + * function assertNumber(v: any): asserts v is number { + * if (typeof v !== 'number') + * throw new TypeError('Nope !') + * } + * + * expectTypeOf(assertNumber).asserts.toBeNumber() + * ``` + */ + asserts: Actual extends (v: any, ...args: any[]) => asserts v is infer T ? unknown extends T ? never : ExpectTypeOf : never; +} +/** + * Represents a function that allows asserting the expected type of a value. + */ +export type _ExpectTypeOf = { + /** + * Asserts the expected type of a value. + * + * @param actual - The actual value being asserted. + * @returns An object representing the expected type assertion. + */ + (actual: Actual): ExpectTypeOf; + /** + * Asserts the expected type of a value without providing an actual value. + * + * @returns An object representing the expected type assertion. + */ + (): ExpectTypeOf; +}; +/** + * Similar to Jest's `expect`, but with type-awareness. + * Gives you access to a number of type-matchers that let you make assertions about the + * form of a reference or generic type parameter. + * + * @example + * ```ts + * import { foo, bar } from '../foo' + * import { expectTypeOf } from 'expect-type' + * + * test('foo types', () => { + * // make sure `foo` has type { a: number } + * expectTypeOf(foo).toMatchTypeOf({ a: 1 }) + * expectTypeOf(foo).toHaveProperty('a').toBeNumber() + * + * // make sure `bar` is a function taking a string: + * expectTypeOf(bar).parameter(0).toBeString() + * expectTypeOf(bar).returns.not.toBeAny() + * }) + * ``` + * + * @description + * See the [full docs](https://npmjs.com/package/expect-type#documentation) for lots more examples. + */ +export declare const expectTypeOf: _ExpectTypeOf; diff --git a/node_modules/expect-type/dist/index.js b/node_modules/expect-type/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..55e299ec5099998e5bfd3c25b037296d7ceee0a2 --- /dev/null +++ b/node_modules/expect-type/dist/index.js @@ -0,0 +1,96 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.expectTypeOf = void 0; +__exportStar(require("./branding"), exports); // backcompat, consider removing in next major version +__exportStar(require("./messages"), exports); // backcompat, consider removing in next major version +__exportStar(require("./overloads"), exports); +__exportStar(require("./utils"), exports); // backcompat, consider removing in next major version +const fn = () => true; +/** + * Similar to Jest's `expect`, but with type-awareness. + * Gives you access to a number of type-matchers that let you make assertions about the + * form of a reference or generic type parameter. + * + * @example + * ```ts + * import { foo, bar } from '../foo' + * import { expectTypeOf } from 'expect-type' + * + * test('foo types', () => { + * // make sure `foo` has type { a: number } + * expectTypeOf(foo).toMatchTypeOf({ a: 1 }) + * expectTypeOf(foo).toHaveProperty('a').toBeNumber() + * + * // make sure `bar` is a function taking a string: + * expectTypeOf(bar).parameter(0).toBeString() + * expectTypeOf(bar).returns.not.toBeAny() + * }) + * ``` + * + * @description + * See the [full docs](https://npmjs.com/package/expect-type#documentation) for lots more examples. + */ +const expectTypeOf = (_actual) => { + const nonFunctionProperties = [ + 'parameters', + 'returns', + 'resolves', + 'not', + 'items', + 'constructorParameters', + 'thisParameter', + 'instance', + 'guards', + 'asserts', + 'branded', + ]; + const obj = { + /* eslint-disable @typescript-eslint/no-unsafe-assignment */ + toBeAny: fn, + toBeUnknown: fn, + toBeNever: fn, + toBeFunction: fn, + toBeObject: fn, + toBeArray: fn, + toBeString: fn, + toBeNumber: fn, + toBeBoolean: fn, + toBeVoid: fn, + toBeSymbol: fn, + toBeNull: fn, + toBeUndefined: fn, + toBeNullable: fn, + toBeBigInt: fn, + toMatchTypeOf: fn, + toEqualTypeOf: fn, + toBeConstructibleWith: fn, + toMatchObjectType: fn, + toExtend: fn, + map: exports.expectTypeOf, + toBeCallableWith: exports.expectTypeOf, + extract: exports.expectTypeOf, + exclude: exports.expectTypeOf, + pick: exports.expectTypeOf, + omit: exports.expectTypeOf, + toHaveProperty: exports.expectTypeOf, + parameter: exports.expectTypeOf, + }; + const getterProperties = nonFunctionProperties; + getterProperties.forEach((prop) => Object.defineProperty(obj, prop, { get: () => (0, exports.expectTypeOf)({}) })); + return obj; +}; +exports.expectTypeOf = expectTypeOf; diff --git a/node_modules/expect-type/dist/messages.d.ts b/node_modules/expect-type/dist/messages.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d8de9bedd70e8fec408d3375d416c0d681929cdc --- /dev/null +++ b/node_modules/expect-type/dist/messages.d.ts @@ -0,0 +1,168 @@ +import type { StrictEqualUsingBranding } from './branding'; +import type { And, Extends, ExtendsExcludingAnyOrNever, IsAny, IsNever, IsUnknown, Not, OptionalKeys, UsefulKeys } from './utils'; +/** + * Determines the printable type representation for a given type. + */ +export type PrintType = IsUnknown extends true ? 'unknown' : IsNever extends true ? 'never' : IsAny extends true ? never : boolean extends T ? 'boolean' : T extends boolean ? `literal boolean: ${T}` : string extends T ? 'string' : T extends string ? `literal string: ${T}` : number extends T ? 'number' : T extends number ? `literal number: ${T}` : bigint extends T ? 'bigint' : T extends bigint ? `literal bigint: ${T}` : T extends null ? 'null' : T extends undefined ? 'undefined' : T extends (...args: any[]) => any ? 'function' : '...'; +/** + * Helper for showing end-user a hint why their type assertion is failing. + * This swaps "leaf" types with a literal message about what the actual and + * expected types are. Needs to check for `Not>` because + * otherwise `LeafTypeOf` returns `never`, which extends everything 🤔 + */ +export type MismatchInfo = And<[Extends, '...'>, Not>]> extends true ? And<[Extends, Extends]> extends true ? Array[number], Extract[number]>> : Optionalify<{ + [K in UsefulKeys | UsefulKeys]: MismatchInfo; +}, OptionalKeys> : StrictEqualUsingBranding extends true ? Actual : `Expected: ${PrintType}, Actual: ${PrintType>}`; +/** + * Helper for making some keys of a type optional. Only useful so far for `MismatchInfo` - it makes sure we + * don't get bogus errors about optional properties mismatching, when actually it's something else that's wrong. + * + * - Note: this helper is a no-op if there are no optional keys in the type. + */ +export type Optionalify = [TOptionalKeys] extends [never] ? T : ({ + [K in Exclude]: T[K]; +} & { + [K in Extract]?: T[K]; +}) extends infer X ? { + [K in keyof X]: X[K]; +} : never; +/** + * @internal + */ +declare const inverted: unique symbol; +/** + * @internal + */ +type Inverted = { + [inverted]: T; +}; +/** + * @internal + */ +declare const expectNull: unique symbol; +export type ExpectNull = { + [expectNull]: T; + result: ExtendsExcludingAnyOrNever; +}; +/** + * @internal + */ +declare const expectUndefined: unique symbol; +export type ExpectUndefined = { + [expectUndefined]: T; + result: ExtendsExcludingAnyOrNever; +}; +/** + * @internal + */ +declare const expectNumber: unique symbol; +export type ExpectNumber = { + [expectNumber]: T; + result: ExtendsExcludingAnyOrNever; +}; +/** + * @internal + */ +declare const expectString: unique symbol; +export type ExpectString = { + [expectString]: T; + result: ExtendsExcludingAnyOrNever; +}; +/** + * @internal + */ +declare const expectBoolean: unique symbol; +export type ExpectBoolean = { + [expectBoolean]: T; + result: ExtendsExcludingAnyOrNever; +}; +/** + * @internal + */ +declare const expectVoid: unique symbol; +export type ExpectVoid = { + [expectVoid]: T; + result: ExtendsExcludingAnyOrNever; +}; +/** + * @internal + */ +declare const expectFunction: unique symbol; +export type ExpectFunction = { + [expectFunction]: T; + result: ExtendsExcludingAnyOrNever any>; +}; +/** + * @internal + */ +declare const expectObject: unique symbol; +export type ExpectObject = { + [expectObject]: T; + result: ExtendsExcludingAnyOrNever; +}; +/** + * @internal + */ +declare const expectArray: unique symbol; +export type ExpectArray = { + [expectArray]: T; + result: ExtendsExcludingAnyOrNever; +}; +/** + * @internal + */ +declare const expectSymbol: unique symbol; +export type ExpectSymbol = { + [expectSymbol]: T; + result: ExtendsExcludingAnyOrNever; +}; +/** + * @internal + */ +declare const expectAny: unique symbol; +export type ExpectAny = { + [expectAny]: T; + result: IsAny; +}; +/** + * @internal + */ +declare const expectUnknown: unique symbol; +export type ExpectUnknown = { + [expectUnknown]: T; + result: IsUnknown; +}; +/** + * @internal + */ +declare const expectNever: unique symbol; +export type ExpectNever = { + [expectNever]: T; + result: IsNever; +}; +/** + * @internal + */ +declare const expectNullable: unique symbol; +export type ExpectNullable = { + [expectNullable]: T; + result: Not>>; +}; +/** + * @internal + */ +declare const expectBigInt: unique symbol; +export type ExpectBigInt = { + [expectBigInt]: T; + result: ExtendsExcludingAnyOrNever; +}; +/** + * Checks if the result of an expecter matches the specified options, and + * resolves to a fairly readable error message if not. + */ +export type Scolder = Expecter['result'] extends Options['positive'] ? () => true : Options['positive'] extends true ? Expecter : Inverted; +export {}; diff --git a/node_modules/expect-type/dist/messages.js b/node_modules/expect-type/dist/messages.js new file mode 100644 index 0000000000000000000000000000000000000000..ff4e0ae9d1cc506042d41c1b91cf85e5ed6c93c6 --- /dev/null +++ b/node_modules/expect-type/dist/messages.js @@ -0,0 +1,66 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * @internal + */ +const inverted = Symbol('inverted'); +/** + * @internal + */ +const expectNull = Symbol('expectNull'); +/** + * @internal + */ +const expectUndefined = Symbol('expectUndefined'); +/** + * @internal + */ +const expectNumber = Symbol('expectNumber'); +/** + * @internal + */ +const expectString = Symbol('expectString'); +/** + * @internal + */ +const expectBoolean = Symbol('expectBoolean'); +/** + * @internal + */ +const expectVoid = Symbol('expectVoid'); +/** + * @internal + */ +const expectFunction = Symbol('expectFunction'); +/** + * @internal + */ +const expectObject = Symbol('expectObject'); +/** + * @internal + */ +const expectArray = Symbol('expectArray'); +/** + * @internal + */ +const expectSymbol = Symbol('expectSymbol'); +/** + * @internal + */ +const expectAny = Symbol('expectAny'); +/** + * @internal + */ +const expectUnknown = Symbol('expectUnknown'); +/** + * @internal + */ +const expectNever = Symbol('expectNever'); +/** + * @internal + */ +const expectNullable = Symbol('expectNullable'); +/** + * @internal + */ +const expectBigInt = Symbol('expectBigInt'); diff --git a/node_modules/expect-type/dist/overloads.d.ts b/node_modules/expect-type/dist/overloads.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ab0e22ed8f4a40859c0a9424e9f7a8434086f192 --- /dev/null +++ b/node_modules/expect-type/dist/overloads.d.ts @@ -0,0 +1,288 @@ +import type { StrictEqualUsingTSInternalIdenticalToOperator, IsNever, UnionToIntersection, UnionToTuple } from './utils'; +/** + * The simple(ish) way to get overload info from a function + * {@linkcode FunctionType}. Recent versions of TypeScript will match any + * function against a generic 10-overload type, filling in slots with + * duplicates of the function. So, we can just match against a single type + * and get all the overloads. + * + * For older versions of TypeScript, we'll need to painstakingly do + * ten separate matches. + */ +export type TSPost53OverloadsInfoUnion = FunctionType extends { + (...args: infer A1): infer R1; + (...args: infer A2): infer R2; + (...args: infer A3): infer R3; + (...args: infer A4): infer R4; + (...args: infer A5): infer R5; + (...args: infer A6): infer R6; + (...args: infer A7): infer R7; + (...args: infer A8): infer R8; + (...args: infer A9): infer R9; + (...args: infer A10): infer R10; +} ? ((...p: A1) => R1) | ((...p: A2) => R2) | ((...p: A3) => R3) | ((...p: A4) => R4) | ((...p: A5) => R5) | ((...p: A6) => R6) | ((...p: A7) => R7) | ((...p: A8) => R8) | ((...p: A9) => R9) | ((...p: A10) => R10) : never; +/** + * A function with `unknown` parameters and return type. + */ +export type UnknownFunction = (...args: unknown[]) => unknown; +/** + * `true` iff {@linkcode FunctionType} is + * equivalent to `(...args: unknown[]) => unknown`, + * which is what an overload variant looks like for a non-existent overload. + * This is useful because older versions of TypeScript end up with + * 9 "useless" overloads and one real one for parameterless/generic functions. + * + * @see {@link https://github.com/microsoft/TypeScript/issues/28867 | Related} + */ +export type IsUselessOverloadInfo = StrictEqualUsingTSInternalIdenticalToOperator; +/** + * Old versions of TypeScript can sometimes seem to refuse to separate out + * union members unless you put them each in a pointless tuple and add an + * extra `infer X` expression. There may be a better way to work around this + * problem, but since it's not a problem in newer versions of TypeScript, + * it's not a priority right now. + */ +export type Tuplify = Union extends infer X ? [X] : never; +/** + * For older versions of TypeScript, we need two separate workarounds + * to get overload info. First, we need need to use + * {@linkcode DecreasingOverloadsInfoUnion} to get the overload info for + * functions with 1-10 overloads. Then, we need to filter out the + * "useless" overloads that are present in older versions of TypeScript, + * for parameterless functions. To do this we use + * {@linkcode IsUselessOverloadInfo} to remove useless overloads. + * + * @see {@link https://github.com/microsoft/TypeScript/issues/28867 | Related} + */ +export type TSPre53OverloadsInfoUnion = Tuplify> extends infer Tup ? Tup extends [infer Fn] ? IsUselessOverloadInfo extends true ? never : Fn : never : never; +/** + * For versions of TypeScript below 5.3, we need to check for 10 overloads, + * then 9, then 8, etc., to get a union of the overload variants. + */ +export type DecreasingOverloadsInfoUnion = F extends { + (...args: infer A1): infer R1; + (...args: infer A2): infer R2; + (...args: infer A3): infer R3; + (...args: infer A4): infer R4; + (...args: infer A5): infer R5; + (...args: infer A6): infer R6; + (...args: infer A7): infer R7; + (...args: infer A8): infer R8; + (...args: infer A9): infer R9; + (...args: infer A10): infer R10; +} ? ((...p: A1) => R1) | ((...p: A2) => R2) | ((...p: A3) => R3) | ((...p: A4) => R4) | ((...p: A5) => R5) | ((...p: A6) => R6) | ((...p: A7) => R7) | ((...p: A8) => R8) | ((...p: A9) => R9) | ((...p: A10) => R10) : F extends { + (...args: infer A1): infer R1; + (...args: infer A2): infer R2; + (...args: infer A3): infer R3; + (...args: infer A4): infer R4; + (...args: infer A5): infer R5; + (...args: infer A6): infer R6; + (...args: infer A7): infer R7; + (...args: infer A8): infer R8; + (...args: infer A9): infer R9; +} ? ((...p: A1) => R1) | ((...p: A2) => R2) | ((...p: A3) => R3) | ((...p: A4) => R4) | ((...p: A5) => R5) | ((...p: A6) => R6) | ((...p: A7) => R7) | ((...p: A8) => R8) | ((...p: A9) => R9) : F extends { + (...args: infer A1): infer R1; + (...args: infer A2): infer R2; + (...args: infer A3): infer R3; + (...args: infer A4): infer R4; + (...args: infer A5): infer R5; + (...args: infer A6): infer R6; + (...args: infer A7): infer R7; + (...args: infer A8): infer R8; +} ? ((...p: A1) => R1) | ((...p: A2) => R2) | ((...p: A3) => R3) | ((...p: A4) => R4) | ((...p: A5) => R5) | ((...p: A6) => R6) | ((...p: A7) => R7) | ((...p: A8) => R8) : F extends { + (...args: infer A1): infer R1; + (...args: infer A2): infer R2; + (...args: infer A3): infer R3; + (...args: infer A4): infer R4; + (...args: infer A5): infer R5; + (...args: infer A6): infer R6; + (...args: infer A7): infer R7; +} ? ((...p: A1) => R1) | ((...p: A2) => R2) | ((...p: A3) => R3) | ((...p: A4) => R4) | ((...p: A5) => R5) | ((...p: A6) => R6) | ((...p: A7) => R7) : F extends { + (...args: infer A1): infer R1; + (...args: infer A2): infer R2; + (...args: infer A3): infer R3; + (...args: infer A4): infer R4; + (...args: infer A5): infer R5; + (...args: infer A6): infer R6; +} ? ((...p: A1) => R1) | ((...p: A2) => R2) | ((...p: A3) => R3) | ((...p: A4) => R4) | ((...p: A5) => R5) | ((...p: A6) => R6) : F extends { + (...args: infer A1): infer R1; + (...args: infer A2): infer R2; + (...args: infer A3): infer R3; + (...args: infer A4): infer R4; + (...args: infer A5): infer R5; +} ? ((...p: A1) => R1) | ((...p: A2) => R2) | ((...p: A3) => R3) | ((...p: A4) => R4) | ((...p: A5) => R5) : F extends { + (...args: infer A1): infer R1; + (...args: infer A2): infer R2; + (...args: infer A3): infer R3; + (...args: infer A4): infer R4; +} ? ((...p: A1) => R1) | ((...p: A2) => R2) | ((...p: A3) => R3) | ((...p: A4) => R4) : F extends { + (...args: infer A1): infer R1; + (...args: infer A2): infer R2; + (...args: infer A3): infer R3; +} ? ((...p: A1) => R1) | ((...p: A2) => R2) | ((...p: A3) => R3) : F extends { + (...args: infer A1): infer R1; + (...args: infer A2): infer R2; +} ? ((...p: A1) => R1) | ((...p: A2) => R2) : F extends (...args: infer A1) => infer R1 ? ((...p: A1) => R1) : never; +/** + * Get a union of overload variants for a function {@linkcode FunctionType}. + * Does a check for whether we can do the one-shot + * 10-overload matcher (which works for ts\>5.3), and if not, + * falls back to the more complicated utility. + */ +export type OverloadsInfoUnion = IsNever 2>> extends true ? TSPre53OverloadsInfoUnion : TSPost53OverloadsInfoUnion; +/** + * Allows inferring any function using the `infer` keyword. + */ +export type InferFunctionType any> = FunctionType; +/** + * A union type of the parameters allowed for any + * overload of function {@linkcode FunctionType}. + */ +export type OverloadParameters = OverloadsInfoUnion extends InferFunctionType ? Parameters : never; +/** + * A union type of the return types for any overload of + * function {@linkcode FunctionType}. + */ +export type OverloadReturnTypes = OverloadsInfoUnion extends InferFunctionType ? ReturnType : never; +/** + * Takes an overload variants {@linkcode Union}, + * produced from {@linkcode OverloadsInfoUnion} and rejects + * the ones incompatible with parameters {@linkcode Args}. + */ +export type SelectOverloadsInfo = Union extends InferFunctionType ? (Args extends Parameters ? Fn : never) : never; +/** + * Creates a new overload (an intersection type) from an existing one, + * which only includes variant(s) which can accept + * {@linkcode Args} as parameters. + */ +export type OverloadsNarrowedByParameters> = UnionToIntersection, Args>>; +/** + * The simple(ish) way to get overload info from a constructor + * {@linkcode ConstructorType}. Recent versions of TypeScript will match any + * constructor against a generic 10-overload type, filling in slots with + * duplicates of the constructor. So, we can just match against a single type + * and get all the overloads. + * + * For older versions of TypeScript, + * we'll need to painstakingly do ten separate matches. + */ +export type TSPost53ConstructorOverloadsInfoUnion = ConstructorType extends { + new (...args: infer A1): infer R1; + new (...args: infer A2): infer R2; + new (...args: infer A3): infer R3; + new (...args: infer A4): infer R4; + new (...args: infer A5): infer R5; + new (...args: infer A6): infer R6; + new (...args: infer A7): infer R7; + new (...args: infer A8): infer R8; + new (...args: infer A9): infer R9; + new (...args: infer A10): infer R10; +} ? (new (...p: A1) => R1) | (new (...p: A2) => R2) | (new (...p: A3) => R3) | (new (...p: A4) => R4) | (new (...p: A5) => R5) | (new (...p: A6) => R6) | (new (...p: A7) => R7) | (new (...p: A8) => R8) | (new (...p: A9) => R9) | (new (...p: A10) => R10) : never; +/** + * A constructor function with `unknown` parameters and return type. + */ +export type UnknownConstructor = new (...args: unknown[]) => unknown; +/** + * Same as {@linkcode IsUselessOverloadInfo}, but for constructors. + */ +export type IsUselessConstructorOverloadInfo = StrictEqualUsingTSInternalIdenticalToOperator; +/** + * For older versions of TypeScript, we need two separate workarounds to + * get constructor overload info. First, we need need to use + * {@linkcode DecreasingConstructorOverloadsInfoUnion} to get the overload + * info for constructors with 1-10 overloads. Then, we need to filter out the + * "useless" overloads that are present in older versions of TypeScript, + * for parameterless constructors. To do this we use + * {@linkcode IsUselessConstructorOverloadInfo} to remove useless overloads. + * + * @see {@link https://github.com/microsoft/TypeScript/issues/28867 | Related} + */ +export type TSPre53ConstructorOverloadsInfoUnion = Tuplify> extends infer Tup ? Tup extends [infer Ctor] ? IsUselessConstructorOverloadInfo extends true ? never : Ctor : never : never; +/** + * For versions of TypeScript below 5.3, we need to check for 10 overloads, + * then 9, then 8, etc., to get a union of the overload variants. + */ +export type DecreasingConstructorOverloadsInfoUnion = ConstructorType extends { + new (...args: infer A1): infer R1; + new (...args: infer A2): infer R2; + new (...args: infer A3): infer R3; + new (...args: infer A4): infer R4; + new (...args: infer A5): infer R5; + new (...args: infer A6): infer R6; + new (...args: infer A7): infer R7; + new (...args: infer A8): infer R8; + new (...args: infer A9): infer R9; + new (...args: infer A10): infer R10; +} ? (new (...p: A1) => R1) | (new (...p: A2) => R2) | (new (...p: A3) => R3) | (new (...p: A4) => R4) | (new (...p: A5) => R5) | (new (...p: A6) => R6) | (new (...p: A7) => R7) | (new (...p: A8) => R8) | (new (...p: A9) => R9) | (new (...p: A10) => R10) : ConstructorType extends { + new (...args: infer A1): infer R1; + new (...args: infer A2): infer R2; + new (...args: infer A3): infer R3; + new (...args: infer A4): infer R4; + new (...args: infer A5): infer R5; + new (...args: infer A6): infer R6; + new (...args: infer A7): infer R7; + new (...args: infer A8): infer R8; + new (...args: infer A9): infer R9; +} ? (new (...p: A1) => R1) | (new (...p: A2) => R2) | (new (...p: A3) => R3) | (new (...p: A4) => R4) | (new (...p: A5) => R5) | (new (...p: A6) => R6) | (new (...p: A7) => R7) | (new (...p: A8) => R8) | (new (...p: A9) => R9) : ConstructorType extends { + new (...args: infer A1): infer R1; + new (...args: infer A2): infer R2; + new (...args: infer A3): infer R3; + new (...args: infer A4): infer R4; + new (...args: infer A5): infer R5; + new (...args: infer A6): infer R6; + new (...args: infer A7): infer R7; + new (...args: infer A8): infer R8; +} ? (new (...p: A1) => R1) | (new (...p: A2) => R2) | (new (...p: A3) => R3) | (new (...p: A4) => R4) | (new (...p: A5) => R5) | (new (...p: A6) => R6) | (new (...p: A7) => R7) | (new (...p: A8) => R8) : ConstructorType extends { + new (...args: infer A1): infer R1; + new (...args: infer A2): infer R2; + new (...args: infer A3): infer R3; + new (...args: infer A4): infer R4; + new (...args: infer A5): infer R5; + new (...args: infer A6): infer R6; + new (...args: infer A7): infer R7; +} ? (new (...p: A1) => R1) | (new (...p: A2) => R2) | (new (...p: A3) => R3) | (new (...p: A4) => R4) | (new (...p: A5) => R5) | (new (...p: A6) => R6) | (new (...p: A7) => R7) : ConstructorType extends { + new (...args: infer A1): infer R1; + new (...args: infer A2): infer R2; + new (...args: infer A3): infer R3; + new (...args: infer A4): infer R4; + new (...args: infer A5): infer R5; + new (...args: infer A6): infer R6; +} ? (new (...p: A1) => R1) | (new (...p: A2) => R2) | (new (...p: A3) => R3) | (new (...p: A4) => R4) | (new (...p: A5) => R5) | (new (...p: A6) => R6) : ConstructorType extends { + new (...args: infer A1): infer R1; + new (...args: infer A2): infer R2; + new (...args: infer A3): infer R3; + new (...args: infer A4): infer R4; + new (...args: infer A5): infer R5; +} ? (new (...p: A1) => R1) | (new (...p: A2) => R2) | (new (...p: A3) => R3) | (new (...p: A4) => R4) | (new (...p: A5) => R5) : ConstructorType extends { + new (...args: infer A1): infer R1; + new (...args: infer A2): infer R2; + new (...args: infer A3): infer R3; + new (...args: infer A4): infer R4; +} ? (new (...p: A1) => R1) | (new (...p: A2) => R2) | (new (...p: A3) => R3) | (new (...p: A4) => R4) : ConstructorType extends { + new (...args: infer A1): infer R1; + new (...args: infer A2): infer R2; + new (...args: infer A3): infer R3; +} ? (new (...p: A1) => R1) | (new (...p: A2) => R2) | (new (...p: A3) => R3) : ConstructorType extends { + new (...args: infer A1): infer R1; + new (...args: infer A2): infer R2; +} ? (new (...p: A1) => R1) | (new (...p: A2) => R2) : ConstructorType extends new (...args: infer A1) => infer R1 ? (new (...p: A1) => R1) : never; +/** + * Get a union of overload variants for a constructor + * {@linkcode ConstructorType}. Does a check for whether we can do the + * one-shot 10-overload matcher (which works for ts\>5.3), and if not, + * falls back to the more complicated utility. + */ +export type ConstructorOverloadsUnion = IsNever any>> extends true ? TSPre53ConstructorOverloadsInfoUnion : TSPost53ConstructorOverloadsInfoUnion; +/** + * Allows inferring any constructor using the `infer` keyword. + */ +export type InferConstructor any> = ConstructorType; +/** + * A union type of the parameters allowed for any overload + * of constructor {@linkcode ConstructorType}. + */ +export type ConstructorOverloadParameters = ConstructorOverloadsUnion extends InferConstructor ? ConstructorParameters : never; +/** + * Calculates the number of overloads for a given function type. + */ +export type NumOverloads = UnionToTuple>['length']; diff --git a/node_modules/expect-type/dist/overloads.js b/node_modules/expect-type/dist/overloads.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/expect-type/dist/overloads.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/expect-type/dist/utils.d.ts b/node_modules/expect-type/dist/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..255624b43360e22825aeb9b007a63e4c94c49023 --- /dev/null +++ b/node_modules/expect-type/dist/utils.d.ts @@ -0,0 +1,197 @@ +/** + * Negates a boolean type. + */ +export type Not = T extends true ? false : true; +/** + * Returns `true` if at least one of the types in the + * {@linkcode Types} array is `true`, otherwise returns `false`. + */ +export type Or = Types[number] extends false ? false : true; +/** + * Checks if all the boolean types in the {@linkcode Types} array are `true`. + */ +export type And = Types[number] extends true ? true : false; +/** + * Represents an equality type that returns {@linkcode Right} if + * {@linkcode Left} is `true`, + * otherwise returns the negation of {@linkcode Right}. + */ +export type Eq = Left extends true ? Right : Not; +/** + * Represents the exclusive OR operation on a tuple of boolean types. + * Returns `true` if exactly one of the boolean types is `true`, + * otherwise returns `false`. + */ +export type Xor = Not>; +/** + * @internal + */ +declare const secret: unique symbol; +/** + * @internal + */ +type Secret = typeof secret; +/** + * Checks if the given type is `never`. + */ +export type IsNever = [T] extends [never] ? true : false; +/** + * Checks if the given type is `any`. + */ +export type IsAny = [T] extends [Secret] ? Not> : false; +/** + * Determines if the given type is `unknown`. + */ +export type IsUnknown = [unknown] extends [T] ? Not> : false; +/** + * Determines if a type is either `never` or `any`. + */ +export type IsNeverOrAny = Or<[IsNever, IsAny]>; +/** + * Subjective "useful" keys from a type. For objects it's just `keyof` but for + * tuples/arrays it's the number keys. + * + * @example + * ```ts + * UsefulKeys<{ a: 1; b: 2 }> // 'a' | 'b' + * + * UsefulKeys<['a', 'b']> // '0' | '1' + * + * UsefulKeys // number + * ``` + */ +export type UsefulKeys = T extends any[] ? { + [K in keyof T]: K; +}[number] : keyof T; +/** + * Extracts the keys from a type that are required (not optional). + */ +export type RequiredKeys = Extract<{ + [K in keyof T]-?: {} extends Pick ? never : K; +}[keyof T], keyof T>; +/** + * Gets the keys of an object type that are optional. + */ +export type OptionalKeys = Exclude>; +/** + * Extracts the keys from a type that are not `readonly`. + */ +export type ReadonlyKeys = Extract<{ + [K in keyof T]-?: ReadonlyEquivalent<{ + [_K in K]: T[K]; + }, { + -readonly [_K in K]: T[K]; + }> extends true ? never : K; +}[keyof T], keyof T>; +/** + * Determines if two types, are equivalent in a `readonly` manner. + * + * @internal + */ +type ReadonlyEquivalent = Extends<(() => T extends X ? true : false), (() => T extends Y ? true : false)>; +/** + * Checks if one type extends another. Note: this is not quite the same as `Left extends Right` because: + * 1. If either type is `never`, the result is `true` iff the other type is also `never`. + * 2. Types are wrapped in a 1-tuple so that union types are not distributed - instead we consider `string | number` to _not_ extend `number`. If we used `Left extends Right` directly you would get `Extends` => `false | true` => `boolean`. + */ +export type Extends = IsNever extends true ? IsNever : [Left] extends [Right] ? true : false; +/** + * Checks if the {@linkcode Left} type extends the {@linkcode Right} type, + * excluding `any` or `never`. + */ +export type ExtendsExcludingAnyOrNever = IsAny extends true ? IsAny : Extends; +/** + * Checks if two types are strictly equal using + * the TypeScript internal identical-to operator. + * + * @see {@link https://github.com/microsoft/TypeScript/issues/55188#issuecomment-1656328122 | much history} + */ +export type StrictEqualUsingTSInternalIdenticalToOperator = (() => T extends (L & T) | T ? true : false) extends () => T extends (R & T) | T ? true : false ? IsNever extends IsNever ? true : false : false; +/** + * Checks that {@linkcode Left} and {@linkcode Right} extend each other. + * Not quite the same as an equality check since `any` can make it resolve + * to `true`. So should only be used when {@linkcode Left} and + * {@linkcode Right} are known to avoid `any`. + */ +export type MutuallyExtends = And<[Extends, Extends]>; +/** + * @internal + */ +declare const mismatch: unique symbol; +/** + * @internal + */ +type Mismatch = { + [mismatch]: 'mismatch'; +}; +/** + * A type which should match anything passed as a value but *doesn't* + * match {@linkcode Mismatch}. It helps TypeScript select the right overload + * for {@linkcode PositiveExpectTypeOf.toEqualTypeOf | .toEqualTypeOf()} and + * {@linkcode PositiveExpectTypeOf.toMatchTypeOf | .toMatchTypeOf()}. + * + * @internal + */ +declare const avalue: unique symbol; +/** + * Represents a value that can be of various types. + */ +export type AValue = { + [avalue]?: undefined; +} | string | number | boolean | symbol | bigint | null | undefined | void; +/** + * Represents the type of mismatched arguments between + * the actual result and the expected result. + * + * If {@linkcode ActualResult} and {@linkcode ExpectedResult} are equivalent, + * the type resolves to an empty tuple `[]`, indicating no mismatch. + * If they are not equivalent, it resolves to a tuple containing the element + * {@linkcode Mismatch}, signifying a discrepancy between + * the expected and actual results. + */ +export type MismatchArgs = Eq extends true ? [] : [Mismatch]; +/** + * Represents the options for the {@linkcode ExpectTypeOf} function. + */ +export interface ExpectTypeOfOptions { + positive: boolean; + branded: boolean; +} +/** + * Convert a union to an intersection. + * `A | B | C` -\> `A & B & C` + */ +export type UnionToIntersection = (Union extends any ? (distributedUnion: Union) => void : never) extends (mergedIntersection: infer Intersection) => void ? Intersection : never; +/** + * Get the last element of a union. + * First, converts to a union of `() => T` functions, + * then uses {@linkcode UnionToIntersection} to get the last one. + */ +export type LastOf = UnionToIntersection Union : never> extends () => infer R ? R : never; +/** + * Intermediate type for {@linkcode UnionToTuple} which pushes the + * "last" union member to the end of a tuple, and recursively prepends + * the remainder of the union. + */ +export type TuplifyUnion> = IsNever extends true ? [] : [...TuplifyUnion>, LastElement]; +/** + * Convert a union like `1 | 2 | 3` to a tuple like `[1, 2, 3]`. + */ +export type UnionToTuple = TuplifyUnion; +export type IsTuple = Or<[Extends, Extends]>; +export type IsUnion = Not['length'], 1>>; +/** + * A recursive version of `Pick` that selects properties from the left type that are present in the right type. + * The "leaf" types from `Left` are used - only the keys of `Right` are considered. + * + * @example + * ```ts + * const user = {email: 'a@b.com', name: 'John Doe', address: {street: '123 2nd St', city: 'New York', zip: '10001', state: 'NY', country: 'USA'}} + * + * type Result = DeepPickMatchingProps // {name: string, address: {city: string}} + * ``` + */ +export type DeepPickMatchingProps = Left extends Record ? Pick<{ + [K in keyof Left]: K extends keyof Right ? DeepPickMatchingProps : never; +}, Extract> : Left; +export {}; diff --git a/node_modules/expect-type/dist/utils.js b/node_modules/expect-type/dist/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..43407cf45b806043a9d50df1746d538077bfeac4 --- /dev/null +++ b/node_modules/expect-type/dist/utils.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * @internal + */ +const secret = Symbol('secret'); +/** + * @internal + */ +const mismatch = Symbol('mismatch'); +/** + * A type which should match anything passed as a value but *doesn't* + * match {@linkcode Mismatch}. It helps TypeScript select the right overload + * for {@linkcode PositiveExpectTypeOf.toEqualTypeOf | .toEqualTypeOf()} and + * {@linkcode PositiveExpectTypeOf.toMatchTypeOf | .toMatchTypeOf()}. + * + * @internal + */ +const avalue = Symbol('avalue'); diff --git a/node_modules/expect-type/package.json b/node_modules/expect-type/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8cc48b4765abaab89342a788af735086bd8f15e6 --- /dev/null +++ b/node_modules/expect-type/package.json @@ -0,0 +1,50 @@ +{ + "name": "expect-type", + "version": "1.3.0", + "engines": { + "node": ">=12.0.0" + }, + "keywords": [ + "typescript", + "type-check", + "assert", + "types", + "typings", + "test", + "testing" + ], + "homepage": "https://github.com/mmkal/expect-type#readme", + "repository": { + "type": "git", + "url": "https://github.com/mmkal/expect-type.git" + }, + "license": "Apache-2.0", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "files": [ + "dist", + "*.md" + ], + "devDependencies": { + "@arethetypeswrong/cli": "0.17.3", + "@types/node": "^22.0.0", + "@typescript/native-preview": "7.0.0-dev.20250527.1", + "@vitest/ui": "^3.0.0", + "eslint": "^8.57.0", + "eslint-plugin-mmkal": "0.9.0", + "np": "^10.2.0", + "pkg-pr-new": "0.0.39", + "strip-ansi": "7.1.0", + "ts-morph": "23.0.0", + "typescript": "5.9.2", + "vitest": "^3.0.0" + }, + "scripts": { + "eslint": "eslint --max-warnings 0", + "lint": "tsc && pnpm eslint .", + "type-check": "tsc", + "build": "tsc -p tsconfig.lib.json", + "arethetypeswrong": "attw --pack", + "test": "vitest run" + } +} \ No newline at end of file diff --git a/node_modules/extend/.editorconfig b/node_modules/extend/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..bc228f8269443bf772b437890dde7756a3e8a894 --- /dev/null +++ b/node_modules/extend/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/node_modules/extend/.eslintrc b/node_modules/extend/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..a34cf2831b7c383001ea86570f8b63686c285c60 --- /dev/null +++ b/node_modules/extend/.eslintrc @@ -0,0 +1,17 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "complexity": [2, 20], + "eqeqeq": [2, "allow-null"], + "func-name-matching": [1], + "max-depth": [1, 4], + "max-statements": [2, 26], + "no-extra-parens": [1], + "no-magic-numbers": [0], + "no-restricted-syntax": [2, "BreakStatement", "ContinueStatement", "DebuggerStatement", "LabeledStatement", "WithStatement"], + "sort-keys": [0], + } +} diff --git a/node_modules/extend/.jscs.json b/node_modules/extend/.jscs.json new file mode 100644 index 0000000000000000000000000000000000000000..3cce01d7832943debaf60e58033d8a110daacbca --- /dev/null +++ b/node_modules/extend/.jscs.json @@ -0,0 +1,175 @@ +{ + "es3": true, + + "additionalRules": [], + + "requireSemicolons": true, + + "disallowMultipleSpaces": true, + + "disallowIdentifierNames": [], + + "requireCurlyBraces": { + "allExcept": [], + "keywords": ["if", "else", "for", "while", "do", "try", "catch"] + }, + + "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], + + "disallowSpaceAfterKeywords": [], + + "disallowSpaceBeforeComma": true, + "disallowSpaceAfterComma": false, + "disallowSpaceBeforeSemicolon": true, + + "disallowNodeTypes": [ + "DebuggerStatement", + "LabeledStatement", + "SwitchCase", + "SwitchStatement", + "WithStatement" + ], + + "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, + + "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, + "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, + "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, + + "requireSpaceBetweenArguments": true, + + "disallowSpacesInsideParentheses": true, + + "disallowSpacesInsideArrayBrackets": true, + + "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, + + "disallowSpaceAfterObjectKeys": true, + + "requireCommaBeforeLineBreak": true, + + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "requireSpaceAfterPrefixUnaryOperators": [], + + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "requireSpaceBeforePostfixUnaryOperators": [], + + "disallowSpaceBeforeBinaryOperators": [], + "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + + "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + "disallowSpaceAfterBinaryOperators": [], + + "disallowImplicitTypeConversion": ["binary", "string"], + + "disallowKeywords": ["with", "eval"], + + "requireKeywordsOnNewLine": [], + "disallowKeywordsOnNewLine": ["else"], + + "requireLineFeedAtFileEnd": true, + + "disallowTrailingWhitespace": true, + + "disallowTrailingComma": true, + + "excludeFiles": ["node_modules/**", "vendor/**"], + + "disallowMultipleLineStrings": true, + + "requireDotNotation": { "allExcept": ["keywords"] }, + + "requireParenthesesAroundIIFE": true, + + "validateLineBreaks": "LF", + + "validateQuoteMarks": { + "escape": true, + "mark": "'" + }, + + "disallowOperatorBeforeLineBreak": [], + + "requireSpaceBeforeKeywords": [ + "do", + "for", + "if", + "else", + "switch", + "case", + "try", + "catch", + "finally", + "while", + "with", + "return" + ], + + "validateAlignedFunctionParameters": { + "lineBreakAfterOpeningBraces": true, + "lineBreakBeforeClosingBraces": true + }, + + "requirePaddingNewLinesBeforeExport": true, + + "validateNewlineAfterArrayElements": { + "maximum": 6 + }, + + "requirePaddingNewLinesAfterUseStrict": true, + + "disallowArrowFunctions": true, + + "disallowMultiLineTernary": true, + + "validateOrderInObjectKeys": false, + + "disallowIdenticalDestructuringNames": true, + + "disallowNestedTernaries": { "maxLevel": 1 }, + + "requireSpaceAfterComma": { "allExcept": ["trailing"] }, + "requireAlignedMultilineParams": false, + + "requireSpacesInGenerator": { + "afterStar": true + }, + + "disallowSpacesInGenerator": { + "beforeStar": true + }, + + "disallowVar": false, + + "requireArrayDestructuring": false, + + "requireEnhancedObjectLiterals": false, + + "requireObjectDestructuring": false, + + "requireEarlyReturn": false, + + "requireCapitalizedConstructorsNew": { + "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] + }, + + "requireImportAlphabetized": false, + + "requireSpaceBeforeObjectValues": true, + "requireSpaceBeforeDestructuredValues": true, + + "disallowSpacesInsideTemplateStringPlaceholders": true, + + "disallowArrayDestructuringReturn": false, + + "requireNewlineBeforeSingleStatementsInIf": false, + + "disallowUnusedVariables": true, + + "requireSpacesInsideImportedObjectBraces": true, + + "requireUseStrict": true +} + diff --git a/node_modules/extend/.travis.yml b/node_modules/extend/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..5ccdfc4948155fbc286e92c049aa2a4468858762 --- /dev/null +++ b/node_modules/extend/.travis.yml @@ -0,0 +1,230 @@ +language: node_js +os: + - linux +node_js: + - "10.7" + - "9.11" + - "8.11" + - "7.10" + - "6.14" + - "5.12" + - "4.9" + - "iojs-v3.3" + - "iojs-v2.5" + - "iojs-v1.8" + - "0.12" + - "0.10" + - "0.8" +before_install: + - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' + - 'nvm install-latest-npm' +install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' +script: + - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' + - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "lts/*" + env: PRETEST=true + - node_js: "lts/*" + env: POSTTEST=true + - node_js: "4" + env: COVERAGE=true + - node_js: "10.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.4" + env: TEST=true ALLOW_FAILURE=true + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true diff --git a/node_modules/extend/CHANGELOG.md b/node_modules/extend/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..2cf7de6fb3ae5dc0c67aeb92f2d6969adc36630d --- /dev/null +++ b/node_modules/extend/CHANGELOG.md @@ -0,0 +1,83 @@ +3.0.2 / 2018-07-19 +================== + * [Fix] Prevent merging `__proto__` property (#48) + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` + * [Tests] up to `node` `v10.7`, `v9.11`, `v8.11`, `v7.10`, `v6.14`, `v4.9`; use `nvm install-latest-npm` + +3.0.1 / 2017-04-27 +================== + * [Fix] deep extending should work with a non-object (#46) + * [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config` + * [Tests] up to `node` `v7.9`, `v6.10`, `v4.8`; improve matrix + * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. + * [Docs] Add example to readme (#34) + +3.0.0 / 2015-07-01 +================== + * [Possible breaking change] Use global "strict" directive (#32) + * [Tests] `int` is an ES3 reserved word + * [Tests] Test up to `io.js` `v2.3` + * [Tests] Add `npm run eslint` + * [Dev Deps] Update `covert`, `jscs` + +2.0.1 / 2015-04-25 +================== + * Use an inline `isArray` check, for ES3 browsers. (#27) + * Some old browsers fail when an identifier is `toString` + * Test latest `node` and `io.js` versions on `travis-ci`; speed up builds + * Add license info to package.json (#25) + * Update `tape`, `jscs` + * Adding a CHANGELOG + +2.0.0 / 2014-10-01 +================== + * Increase code coverage to 100%; run code coverage as part of tests + * Add `npm run lint`; Run linter as part of tests + * Remove nodeType and setInterval checks in isPlainObject + * Updating `tape`, `jscs`, `covert` + * General style and README cleanup + +1.3.0 / 2014-06-20 +================== + * Add component.json for browser support (#18) + * Use SVG for badges in README (#16) + * Updating `tape`, `covert` + * Updating travis-ci to work with multiple node versions + * Fix `deep === false` bug (returning target as {}) (#14) + * Fixing constructor checks in isPlainObject + * Adding additional test coverage + * Adding `npm run coverage` + * Add LICENSE (#13) + * Adding a warning about `false`, per #11 + * General style and whitespace cleanup + +1.2.1 / 2013-09-14 +================== + * Fixing hasOwnProperty bugs that would only have shown up in specific browsers. Fixes #8 + * Updating `tape` + +1.2.0 / 2013-09-02 +================== + * Updating the README: add badges + * Adding a missing variable reference. + * Using `tape` instead of `buster` for tests; add more tests (#7) + * Adding node 0.10 to Travis CI (#6) + * Enabling "npm test" and cleaning up package.json (#5) + * Add Travis CI. + +1.1.3 / 2012-12-06 +================== + * Added unit tests. + * Ensure extend function is named. (Looks nicer in a stack trace.) + * README cleanup. + +1.1.1 / 2012-11-07 +================== + * README cleanup. + * Added installation instructions. + * Added a missing semicolon + +1.0.0 / 2012-04-08 +================== + * Initial commit + diff --git a/node_modules/extend/LICENSE b/node_modules/extend/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e16d6a56ca64e235d9065c37f4566a0fe0be28d4 --- /dev/null +++ b/node_modules/extend/LICENSE @@ -0,0 +1,23 @@ +The MIT License (MIT) + +Copyright (c) 2014 Stefan Thomas + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/extend/README.md b/node_modules/extend/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5b8249aa95e5d34927c0b44988b29fcda85cb1cd --- /dev/null +++ b/node_modules/extend/README.md @@ -0,0 +1,81 @@ +[![Build Status][travis-svg]][travis-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] + +# extend() for Node.js [![Version Badge][npm-version-png]][npm-url] + +`node-extend` is a port of the classic extend() method from jQuery. It behaves as you expect. It is simple, tried and true. + +Notes: + +* Since Node.js >= 4, + [`Object.assign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) + now offers the same functionality natively (but without the "deep copy" option). + See [ECMAScript 2015 (ES6) in Node.js](https://nodejs.org/en/docs/es6). +* Some native implementations of `Object.assign` in both Node.js and many + browsers (since NPM modules are for the browser too) may not be fully + spec-compliant. + Check [`object.assign`](https://www.npmjs.com/package/object.assign) module for + a compliant candidate. + +## Installation + +This package is available on [npm][npm-url] as: `extend` + +``` sh +npm install extend +``` + +## Usage + +**Syntax:** extend **(** [`deep`], `target`, `object1`, [`objectN`] **)** + +*Extend one object with one or more others, returning the modified object.* + +**Example:** + +``` js +var extend = require('extend'); +extend(targetObject, object1, object2); +``` + +Keep in mind that the target object will be modified, and will be returned from extend(). + +If a boolean true is specified as the first argument, extend performs a deep copy, recursively copying any objects it finds. Otherwise, the copy will share structure with the original object(s). +Undefined properties are not copied. However, properties inherited from the object's prototype will be copied over. +Warning: passing `false` as the first argument is not supported. + +### Arguments + +* `deep` *Boolean* (optional) +If set, the merge becomes recursive (i.e. deep copy). +* `target` *Object* +The object to extend. +* `object1` *Object* +The object that will be merged into the first. +* `objectN` *Object* (Optional) +More objects to merge into the first. + +## License + +`node-extend` is licensed under the [MIT License][mit-license-url]. + +## Acknowledgements + +All credit to the jQuery authors for perfecting this amazing utility. + +Ported to Node.js by [Stefan Thomas][github-justmoon] with contributions by [Jonathan Buchanan][github-insin] and [Jordan Harband][github-ljharb]. + +[travis-svg]: https://travis-ci.org/justmoon/node-extend.svg +[travis-url]: https://travis-ci.org/justmoon/node-extend +[npm-url]: https://npmjs.org/package/extend +[mit-license-url]: http://opensource.org/licenses/MIT +[github-justmoon]: https://github.com/justmoon +[github-insin]: https://github.com/insin +[github-ljharb]: https://github.com/ljharb +[npm-version-png]: http://versionbadg.es/justmoon/node-extend.svg +[deps-svg]: https://david-dm.org/justmoon/node-extend.svg +[deps-url]: https://david-dm.org/justmoon/node-extend +[dev-deps-svg]: https://david-dm.org/justmoon/node-extend/dev-status.svg +[dev-deps-url]: https://david-dm.org/justmoon/node-extend#info=devDependencies + diff --git a/node_modules/extend/component.json b/node_modules/extend/component.json new file mode 100644 index 0000000000000000000000000000000000000000..1500a2f37181823ef8500854e8bbe613fbc5215a --- /dev/null +++ b/node_modules/extend/component.json @@ -0,0 +1,32 @@ +{ + "name": "extend", + "author": "Stefan Thomas (http://www.justmoon.net)", + "version": "3.0.0", + "description": "Port of jQuery.extend for node.js and the browser.", + "scripts": [ + "index.js" + ], + "contributors": [ + { + "name": "Jordan Harband", + "url": "https://github.com/ljharb" + } + ], + "keywords": [ + "extend", + "clone", + "merge" + ], + "repository" : { + "type": "git", + "url": "https://github.com/justmoon/node-extend.git" + }, + "dependencies": { + }, + "devDependencies": { + "tape" : "~3.0.0", + "covert": "~0.4.0", + "jscs": "~1.6.2" + } +} + diff --git a/node_modules/extend/index.js b/node_modules/extend/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2aa3faae68c43e0221134e0ee72a713fd7d47a5f --- /dev/null +++ b/node_modules/extend/index.js @@ -0,0 +1,117 @@ +'use strict'; + +var hasOwn = Object.prototype.hasOwnProperty; +var toStr = Object.prototype.toString; +var defineProperty = Object.defineProperty; +var gOPD = Object.getOwnPropertyDescriptor; + +var isArray = function isArray(arr) { + if (typeof Array.isArray === 'function') { + return Array.isArray(arr); + } + + return toStr.call(arr) === '[object Array]'; +}; + +var isPlainObject = function isPlainObject(obj) { + if (!obj || toStr.call(obj) !== '[object Object]') { + return false; + } + + var hasOwnConstructor = hasOwn.call(obj, 'constructor'); + var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); + // Not own constructor property must be Object + if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + var key; + for (key in obj) { /**/ } + + return typeof key === 'undefined' || hasOwn.call(obj, key); +}; + +// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target +var setProperty = function setProperty(target, options) { + if (defineProperty && options.name === '__proto__') { + defineProperty(target, options.name, { + enumerable: true, + configurable: true, + value: options.newValue, + writable: true + }); + } else { + target[options.name] = options.newValue; + } +}; + +// Return undefined instead of __proto__ if '__proto__' is not an own property +var getProperty = function getProperty(obj, name) { + if (name === '__proto__') { + if (!hasOwn.call(obj, name)) { + return void 0; + } else if (gOPD) { + // In early versions of node, obj['__proto__'] is buggy when obj has + // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. + return gOPD(obj, name).value; + } + } + + return obj[name]; +}; + +module.exports = function extend() { + var options, name, src, copy, copyIsArray, clone; + var target = arguments[0]; + var i = 1; + var length = arguments.length; + var deep = false; + + // Handle a deep copy situation + if (typeof target === 'boolean') { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { + target = {}; + } + + for (; i < length; ++i) { + options = arguments[i]; + // Only deal with non-null/undefined values + if (options != null) { + // Extend the base object + for (name in options) { + src = getProperty(target, name); + copy = getProperty(options, name); + + // Prevent never-ending loop + if (target !== copy) { + // Recurse if we're merging plain objects or arrays + if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { + if (copyIsArray) { + copyIsArray = false; + clone = src && isArray(src) ? src : []; + } else { + clone = src && isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); + + // Don't bring in undefined values + } else if (typeof copy !== 'undefined') { + setProperty(target, { name: name, newValue: copy }); + } + } + } + } + } + + // Return the modified object + return target; +}; diff --git a/node_modules/extend/package.json b/node_modules/extend/package.json new file mode 100644 index 0000000000000000000000000000000000000000..85279f78054e5cc6d7f9899afaf9fca60b77d740 --- /dev/null +++ b/node_modules/extend/package.json @@ -0,0 +1,42 @@ +{ + "name": "extend", + "author": "Stefan Thomas (http://www.justmoon.net)", + "version": "3.0.2", + "description": "Port of jQuery.extend for node.js and the browser", + "main": "index", + "scripts": { + "pretest": "npm run lint", + "test": "npm run tests-only", + "posttest": "npm run coverage-quiet", + "tests-only": "node test", + "coverage": "covert test/index.js", + "coverage-quiet": "covert test/index.js --quiet", + "lint": "npm run jscs && npm run eslint", + "jscs": "jscs *.js */*.js", + "eslint": "eslint *.js */*.js" + }, + "contributors": [ + { + "name": "Jordan Harband", + "url": "https://github.com/ljharb" + } + ], + "keywords": [ + "extend", + "clone", + "merge" + ], + "repository": { + "type": "git", + "url": "https://github.com/justmoon/node-extend.git" + }, + "dependencies": {}, + "devDependencies": { + "@ljharb/eslint-config": "^12.2.1", + "covert": "^1.1.0", + "eslint": "^4.19.1", + "jscs": "^3.0.7", + "tape": "^4.9.1" + }, + "license": "MIT" +} diff --git a/node_modules/fake-indexeddb/LICENSE b/node_modules/fake-indexeddb/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ad44ec8ca3641cddb7e580ade97f9244b71ad40b --- /dev/null +++ b/node_modules/fake-indexeddb/LICENSE @@ -0,0 +1,209 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, and + distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by the + copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all other + entities that control, are controlled by, or are under common control with + that entity. For the purposes of this definition, "control" means (i) the + power, direct or indirect, to cause the direction or management of such + entity, whether by contract or otherwise, or (ii) ownership of + fifty percent (50%) or more of the outstanding shares, or (iii) beneficial + ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity exercising + permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation source, + and configuration files. + + "Object" form shall mean any form resulting from mechanical transformation + or translation of a Source form, including but not limited to compiled + object code, generated documentation, and conversions to + other media types. + + "Work" shall mean the work of authorship, whether in Source or Object + form, made available under the License, as indicated by a copyright notice + that is included in or attached to the work (an example is provided in the + Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object form, + that is based on (or derived from) the Work and for which the editorial + revisions, annotations, elaborations, or other modifications represent, + as a whole, an original work of authorship. For the purposes of this + License, Derivative Works shall not include works that remain separable + from, or merely link (or bind by name) to the interfaces of, the Work and + Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including the original + version of the Work and any modifications or additions to that Work or + Derivative Works thereof, that is intentionally submitted to Licensor for + inclusion in the Work by the copyright owner or by an individual or + Legal Entity authorized to submit on behalf of the copyright owner. + For the purposes of this definition, "submitted" means any form of + electronic, verbal, or written communication sent to the Licensor or its + representatives, including but not limited to communication on electronic + mailing lists, source code control systems, and issue tracking systems + that are managed by, or on behalf of, the Licensor for the purpose of + discussing and improving the Work, but excluding communication that is + conspicuously marked or otherwise designated in writing by the copyright + owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity on + behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. + + Subject to the terms and conditions of this License, each Contributor + hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, + royalty-free, irrevocable copyright license to reproduce, prepare + Derivative Works of, publicly display, publicly perform, sublicense, + and distribute the Work and such Derivative Works in + Source or Object form. + +3. Grant of Patent License. + + Subject to the terms and conditions of this License, each Contributor + hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, + royalty-free, irrevocable (except as stated in this section) patent + license to make, have made, use, offer to sell, sell, import, and + otherwise transfer the Work, where such license applies only to those + patent claims licensable by such Contributor that are necessarily + infringed by their Contribution(s) alone or by combination of their + Contribution(s) with the Work to which such Contribution(s) was submitted. + If You institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work or a + Contribution incorporated within the Work constitutes direct or + contributory patent infringement, then any patent licenses granted to + You under this License for that Work shall terminate as of the date such + litigation is filed. + +4. Redistribution. + + You may reproduce and distribute copies of the Work or Derivative Works + thereof in any medium, with or without modifications, and in Source or + Object form, provided that You meet the following conditions: + + 1. You must give any other recipients of the Work or Derivative Works a + copy of this License; and + + 2. You must cause any modified files to carry prominent notices stating + that You changed the files; and + + 3. You must retain, in the Source form of any Derivative Works that You + distribute, all copyright, patent, trademark, and attribution notices from + the Source form of the Work, excluding those notices that do not pertain + to any part of the Derivative Works; and + + 4. If the Work includes a "NOTICE" text file as part of its distribution, + then any Derivative Works that You distribute must include a readable copy + of the attribution notices contained within such NOTICE file, excluding + those notices that do not pertain to any part of the Derivative Works, + in at least one of the following places: within a NOTICE text file + distributed as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, within a + display generated by the Derivative Works, if and wherever such + third-party notices normally appear. The contents of the NOTICE file are + for informational purposes only and do not modify the License. + You may add Your own attribution notices within Derivative Works that You + distribute, alongside or as an addendum to the NOTICE text from the Work, + provided that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and may + provide additional or different license terms and conditions for use, + reproduction, or distribution of Your modifications, or for any such + Derivative Works as a whole, provided Your use, reproduction, and + distribution of the Work otherwise complies with the conditions + stated in this License. + +5. Submission of Contributions. + + Unless You explicitly state otherwise, any Contribution intentionally + submitted for inclusion in the Work by You to the Licensor shall be under + the terms and conditions of this License, without any additional + terms or conditions. Notwithstanding the above, nothing herein shall + supersede or modify the terms of any separate license agreement you may + have executed with Licensor regarding such Contributions. + +6. Trademarks. + + This License does not grant permission to use the trade names, trademarks, + service marks, or product names of the Licensor, except as required for + reasonable and customary use in describing the origin of the Work and + reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + + Unless required by applicable law or agreed to in writing, Licensor + provides the Work (and each Contributor provides its Contributions) + on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + either express or implied, including, without limitation, any warranties + or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS + FOR A PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any risks + associated with Your exercise of permissions under this License. + +8. Limitation of Liability. + + In no event and under no legal theory, whether in tort + (including negligence), contract, or otherwise, unless required by + applicable law (such as deliberate and grossly negligent acts) or agreed + to in writing, shall any Contributor be liable to You for damages, + including any direct, indirect, special, incidental, or consequential + damages of any character arising as a result of this License or out of + the use or inability to use the Work (including but not limited to damages + for loss of goodwill, work stoppage, computer failure or malfunction, + or any and all other commercial damages or losses), even if such + Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + + While redistributing the Work or Derivative Works thereof, You may choose + to offer, and charge a fee for, acceptance of support, warranty, + indemnity, or other liability obligations and/or rights consistent with + this License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf of any + other Contributor, and only if You agree to indemnify, defend, and hold + each Contributor harmless for any liability incurred by, or claims + asserted against, such Contributor by reason of your accepting any such + warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work + + To apply the Apache License to your work, attach the following boilerplate + notice, with the fields enclosed by brackets "[]" replaced with your own + identifying information. (Don't include the brackets!) The text should be + enclosed in the appropriate comment syntax for the file format. We also + recommend that a file or class name and description of purpose be included + on the same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2017 Jeremy Scheff + + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + or implied. See the License for the specific language governing + permissions and limitations under the License. + diff --git a/node_modules/fake-indexeddb/README.md b/node_modules/fake-indexeddb/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1c8cdbfdaccdacf753698670e69cdf1f2ad4d7ed --- /dev/null +++ b/node_modules/fake-indexeddb/README.md @@ -0,0 +1,245 @@ +# fake-indexeddb + +[![Build Status](https://github.com/dumbmatter/fakeIndexedDB/actions/workflows/test.yml/badge.svg)](https://github.com/dumbmatter/fakeIndexedDB/actions/workflows/test.yml) +[![GitHub Repo stars](https://img.shields.io/github/stars/dumbmatter/fakeIndexedDB)](https://github.com/dumbmatter/fakeIndexedDB) +[![GitHub](https://img.shields.io/github/license/dumbmatter/fakeIndexedDB)](https://github.com/dumbmatter/fakeIndexedDB) +[![npm](https://img.shields.io/npm/v/fake-indexeddb)](https://www.npmjs.com/package/fake-indexeddb) +[![npm](https://img.shields.io/npm/dm/fake-indexeddb)](https://www.npmjs.com/package/fake-indexeddb) + +A pure JS in-memory implementation of [the IndexedDB API](https://w3c.github.io/IndexedDB/). Its main use is testing IndexedDB-dependent code in Node.js. + +## Installation + +```sh +npm install --save-dev fake-indexeddb +``` + +## Use + +Functionally, it works exactly like IndexedDB except data is not persisted to disk. + +The easiest way to use it is to import `fake-indexeddb/auto`, which will put all the IndexedDB variables in the global scope. (Both `import` and `require` are supported, use whichever you like, but the examples here are all `import`.) + +```js +import "fake-indexeddb/auto"; + +var request = indexedDB.open("test", 3); +request.onupgradeneeded = function () { + var db = request.result; + var store = db.createObjectStore("books", {keyPath: "isbn"}); + store.createIndex("by_title", "title", {unique: true}); + + store.put({title: "Quarry Memories", author: "Fred", isbn: 123456}); + store.put({title: "Water Buffaloes", author: "Fred", isbn: 234567}); + store.put({title: "Bedrock Nights", author: "Barney", isbn: 345678}); +} +request.onsuccess = function (event) { + var db = event.target.result; + + var tx = db.transaction("books"); + + tx.objectStore("books").index("by_title").get("Quarry Memories").addEventListener("success", function (event) { + console.log("From index:", event.target.result); + }); + tx.objectStore("books").openCursor(IDBKeyRange.lowerBound(200000)).onsuccess = function (event) { + var cursor = event.target.result; + if (cursor) { + console.log("From cursor:", cursor.value); + cursor.continue(); + } + }; + tx.oncomplete = function () { + console.log("All done!"); + }; +}; +``` + +Alternatively, you can explicitly import individual IndexedDB variables: + +```js +import { + indexedDB, + IDBCursor, + IDBCursorWithValue, + IDBDatabase, + IDBFactory, + IDBIndex, + IDBKeyRange, + IDBObjectStore, + IDBOpenDBRequest, + IDBRequest, + IDBTransaction, + IDBVersionChangeEvent, +} from "fake-indexeddb"; + +// The rest is the same as above. +``` + +Like any imported variable, you can rename it if you want, for instance if you don't want to conflict with built-in IndexedDB variables: + +```js +import { + indexedDB as fakeIndexedDB, +} from "fake-indexeddb"; +``` + +### TypeScript + +As of version 4, fake-indexeddb includes TypeScript types. As you can see in types.d.ts, it's just using TypeScript's built-in IndexedDB types, rather than generating types from the fake-indexeddb code base. The reason I did this is for compatibility with your application code that may already be using TypeScript's IndexedDB types, so if I used something different for fake-indexeddb, it could lead to spurious type errors. In theory this could lead to other errors if there are differences between Typescript's IndexedDB types and fake-indexeddb's API, but currently I'm not aware of any difference. See [issue #23](https://github.com/dumbmatter/fakeIndexedDB/issues/23) for more discussion. + +### Dexie and other IndexedDB API wrappers + +If you import `fake-indexeddb/auto` before importing `dexie`, it should work: + +```js +import "fake-indexeddb/auto"; +import Dexie from "dexie"; + +const db = new Dexie("MyDatabase"); +``` + +The same likely holds true for other IndexedDB API wrappers like idb. + +Alternatively, if you don't want to modify the global scope, then you need to explicitly pass the objects to Dexie: + +```js +import Dexie from "dexie"; +import { indexedDB, IDBKeyRange } from "fake-indexeddb"; + +const db = new Dexie("MyDatabase", { indexedDB: indexedDB, IDBKeyRange: IDBKeyRange }); +``` + +### Jest + +To use fake-indexeddb in a single Jest test suite, require `fake-indexeddb/auto` at the beginning of the test +file, as described above. + +To use it on all Jest tests without having to include it in each file, add the auto setup script to the `setupFiles` in your Jest config: + +```json +{ + "setupFiles": [ + "fake-indexeddb/auto" + ] +} +``` + +### jsdom (often used with Jest) + +As of version 5, fake-indexeddb no longer includes a `structuredClone` polyfill. This mostly affects old environments like unsupported versions of Node.js, but [it also affects jsdom](https://github.com/dumbmatter/fakeIndexedDB/issues/88), which is often used with Jest and other testing frameworks. + +There are a few ways you could work around this. You could include your own `structuredClone` polyfill by installing core-js and importing its polyfill before you use fake-indexeddb: + +```js +import "core-js/stable/structured-clone"; +import "fake-indexeddb/auto"; +``` + +Or, [you could manually include the Node.js `structuredClone` implementation in a jsdom environment](https://github.com/jsdom/jsdom/issues/3363#issuecomment-1467894943): + +```js +// FixJSDOMEnvironment.ts + +import JSDOMEnvironment from 'jest-environment-jsdom'; + +// https://github.com/facebook/jest/blob/v29.4.3/website/versioned_docs/version-29.4/Configuration.md#testenvironment-string +export default class FixJSDOMEnvironment extends JSDOMEnvironment { + constructor(...args: ConstructorParameters) { + super(...args); + + // FIXME https://github.com/jsdom/jsdom/issues/3363 + this.global.structuredClone = structuredClone; + } +} +``` + +```js +// jest.config.js + +/** @type {import('jest').Config} */ +const config = { + testEnvironment: './FixJSDOMEnvironment.ts', +}; + +module.exports = config; +``` + +Hopefully a future version of jsdom will no longer require these workarounds. + +### Wiping/resetting the indexedDB for a fresh state + +If you are keeping your tests completely isolated you might want to "reset" the state of the mocked indexedDB. You can do this by creating a new instance of `IDBFactory`, which lets you have a totally fresh start. + +```js +import "fake-indexeddb/auto"; +import { IDBFactory } from "fake-indexeddb"; + +// Whenever you want a fresh indexedDB +indexedDB = new IDBFactory(); +``` + +### Triggering the `"close"` event + +An `IDBDatabase` will fire a `"close"` event when closed for [abnormal reasons](https://www.w3.org/TR/IndexedDB/#closing-connection), such as the user manually deleting databases in DevTools. If you want to simulate this event for test coverage, you can use `forceCloseDatabase()`: + +```js +import { forceCloseDatabase } from "fake-indexeddb"; + +db.addEventListener("close", () => { + console.log("Forcibly closed!"); +}); +forceCloseDatabase(db); // invokes the event listener +``` + +Note that `forceCloseDatabase()` is not a standard IndexedDB API and is unique to fake-indexeddb. + +### With PhantomJS and other really old environments + +PhantomJS (and other really old environments) are missing tons of modern JavaScript features. In fact, that may be why you use fake-indexeddb in such an environment! Prior to v3.0.0, fake-indexeddb imported core-js and automatically applied its polyfills. However, since most fake-indexeddb users are not using really old environments, I got rid of that runtime dependency in v3.0.0. To work around that, you can import core-js yourself before you import fake-indexeddb, like: + +```js +import "core-js/stable"; +import "fake-indexeddb/auto"; +``` + +## Quality + +Here's a comparison of fake-indexeddb and real browser IndexedDB implementations on [the Web Platform Tests IndexedDB suite](https://wpt.fyi/results/IndexedDB) as of November 7, 2025: + + + + + +| Implementation | Version | Passed | % | +| --- | --- | --- | --- | +| Chrome | 144.0.7514.0 | 1651 | 99.9% | +| Firefox | 146.0a1 | 1498 | 90.6% | +| Safari | 231 preview | 1497 | 90.6% | +| Ladybird | 1.0-cde3941d9f | 1426 | 86.3% | +| fake-indexeddb | 6.2.5 | 1369 | 82.8% | + + +Keep in mind that these tests include a lot of edge cases (such as rare error conditions), so even hitting ~40% likely means that the core IndexedDB functionality is covered. Your app will probably work fine. + +Also note that, for a fair comparison with browsers, these results omit some tests that aren't relevant to Node.js such as web workers and cross-origin isolation. When testing fake-indexeddb, some polyfills are used to simulate a browser environment, such as `File` and `location`. + +> [!NOTE] +> To see how these test results are generated, see [`update-browser-wpt-results.js`](./bin/update-browser-wpt-results.js) and [`run-all.js`](./src/test/web-platform-tests/run-all.js). + +## Potential applications: + +1. Use as a mock database in unit tests. + +2. Use the same API in Node.js and in the browser. + +3. Support IndexedDB in old or crappy browsers. + +4. Somehow use it within a caching layer on top of IndexedDB in the browser, since IndexedDB can be kind of slow. + +5. Abstract the core database functions out, so what is left is a shell that allows the IndexedDB API to easily sit on top of many different backends. + +6. Serve as a playground for experimenting with IndexedDB. + +## License + +Apache 2.0 diff --git a/node_modules/fake-indexeddb/auto.d.ts b/node_modules/fake-indexeddb/auto.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e077c998632f1465048de32a55d5ae991d40403 --- /dev/null +++ b/node_modules/fake-indexeddb/auto.d.ts @@ -0,0 +1 @@ +declare module "fake-indexeddb/auto"; diff --git a/node_modules/fake-indexeddb/auto/index.js b/node_modules/fake-indexeddb/auto/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8a2f7f1e93541e56e3c43217f756e394cd02b727 --- /dev/null +++ b/node_modules/fake-indexeddb/auto/index.js @@ -0,0 +1,52 @@ +const fakeIndexedDB = require("../build/cjs/fakeIndexedDB.js"); +const FDBCursor = require("../build/cjs/FDBCursor.js"); +const FDBCursorWithValue = require("../build/cjs/FDBCursorWithValue.js"); +const FDBDatabase = require("../build/cjs/FDBDatabase.js"); +const FDBFactory = require("../build/cjs/FDBFactory.js"); +const FDBIndex = require("../build/cjs/FDBIndex.js"); +const FDBKeyRange = require("../build/cjs/FDBKeyRange.js"); +const FDBObjectStore = require("../build/cjs/FDBObjectStore.js"); +const FDBRecord = require("../build/cjs/FDBRecord.js"); +const FDBOpenDBRequest = require("../build/cjs/FDBOpenDBRequest.js"); +const FDBRequest = require("../build/cjs/FDBRequest.js"); +const FDBTransaction = require("../build/cjs/FDBTransaction.js"); +const FDBVersionChangeEvent = require("../build/cjs/FDBVersionChangeEvent.js"); + +// http://stackoverflow.com/a/33268326/786644 - works in browser, worker, and Node.js +var globalVar = + typeof window !== "undefined" + ? window + : typeof WorkerGlobalScope !== "undefined" + ? self + : typeof global !== "undefined" + ? global + : Function("return this;")(); + +// Partly match the native behavior for `globalThis.indexedDB`, `globalThis.IDBCursor`, etc. +// Per the IDL, `indexedDB` is readonly but the others are readwrite. For us, though, we want it to still +// be overwritable with `globalThis. = ...`, so we make them all readwrite. +// https://w3c.github.io/IndexedDB/#idl-index +const createPropertyDescriptor = (value) => { + return { + value, + enumerable: false, + configurable: true, + writable: true, + }; +}; + +Object.defineProperties(globalVar, { + indexedDB: createPropertyDescriptor(fakeIndexedDB), + IDBCursor: createPropertyDescriptor(FDBCursor), + IDBCursorWithValue: createPropertyDescriptor(FDBCursorWithValue), + IDBDatabase: createPropertyDescriptor(FDBDatabase), + IDBFactory: createPropertyDescriptor(FDBFactory), + IDBIndex: createPropertyDescriptor(FDBIndex), + IDBKeyRange: createPropertyDescriptor(FDBKeyRange), + IDBObjectStore: createPropertyDescriptor(FDBObjectStore), + IDBOpenDBRequest: createPropertyDescriptor(FDBOpenDBRequest), + IDBRecord: createPropertyDescriptor(FDBRecord), + IDBRequest: createPropertyDescriptor(FDBRequest), + IDBTransaction: createPropertyDescriptor(FDBTransaction), + IDBVersionChangeEvent: createPropertyDescriptor(FDBVersionChangeEvent), +}); diff --git a/node_modules/fake-indexeddb/auto/index.mjs b/node_modules/fake-indexeddb/auto/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..02a132676486b959eda1337b1a06fc344e8216dd --- /dev/null +++ b/node_modules/fake-indexeddb/auto/index.mjs @@ -0,0 +1,52 @@ +import fakeIndexedDB from "../build/esm/fakeIndexedDB.js"; +import FDBCursor from "../build/esm/FDBCursor.js"; +import FDBCursorWithValue from "../build/esm/FDBCursorWithValue.js"; +import FDBDatabase from "../build/esm/FDBDatabase.js"; +import FDBFactory from "../build/esm/FDBFactory.js"; +import FDBIndex from "../build/esm/FDBIndex.js"; +import FDBKeyRange from "../build/esm/FDBKeyRange.js"; +import FDBObjectStore from "../build/esm/FDBObjectStore.js"; +import FDBOpenDBRequest from "../build/esm/FDBOpenDBRequest.js"; +import FDBRecord from "../build/esm/FDBRecord.js"; +import FDBRequest from "../build/esm/FDBRequest.js"; +import FDBTransaction from "../build/esm/FDBTransaction.js"; +import FDBVersionChangeEvent from "../build/esm/FDBVersionChangeEvent.js"; + +// http://stackoverflow.com/a/33268326/786644 - works in browser, worker, and Node.js +var globalVar = + typeof window !== "undefined" + ? window + : typeof WorkerGlobalScope !== "undefined" + ? self + : typeof global !== "undefined" + ? global + : Function("return this;")(); + +// Partly match the native behavior for `globalThis.indexedDB`, `globalThis.IDBCursor`, etc. +// Per the IDL, `indexedDB` is readonly but the others are readwrite. For us, though, we want it to still +// be overwritable with `globalThis. = ...`, so we make them all readwrite. +// https://w3c.github.io/IndexedDB/#idl-index +const createPropertyDescriptor = (value) => { + return { + value, + enumerable: false, + configurable: true, + writable: true, + }; +}; + +Object.defineProperties(globalVar, { + indexedDB: createPropertyDescriptor(fakeIndexedDB), + IDBCursor: createPropertyDescriptor(FDBCursor), + IDBCursorWithValue: createPropertyDescriptor(FDBCursorWithValue), + IDBDatabase: createPropertyDescriptor(FDBDatabase), + IDBFactory: createPropertyDescriptor(FDBFactory), + IDBIndex: createPropertyDescriptor(FDBIndex), + IDBKeyRange: createPropertyDescriptor(FDBKeyRange), + IDBObjectStore: createPropertyDescriptor(FDBObjectStore), + IDBOpenDBRequest: createPropertyDescriptor(FDBOpenDBRequest), + IDBRecord: createPropertyDescriptor(FDBRecord), + IDBRequest: createPropertyDescriptor(FDBRequest), + IDBTransaction: createPropertyDescriptor(FDBTransaction), + IDBVersionChangeEvent: createPropertyDescriptor(FDBVersionChangeEvent), +}); diff --git a/node_modules/fake-indexeddb/auto/package.json b/node_modules/fake-indexeddb/auto/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1cd945a3bfd97ab9befff9b9e468ef791062d59b --- /dev/null +++ b/node_modules/fake-indexeddb/auto/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/fake-indexeddb/build/cjs/FDBCursor.js b/node_modules/fake-indexeddb/build/cjs/FDBCursor.js new file mode 100644 index 0000000000000000000000000000000000000000..af81da1a12353ff9a310c77779b6a7d5fa421f63 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/FDBCursor.js @@ -0,0 +1,480 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _FDBKeyRange = _interopRequireDefault(require("./FDBKeyRange.js")); +var _FDBObjectStore = _interopRequireDefault(require("./FDBObjectStore.js")); +var _cmp = _interopRequireDefault(require("./lib/cmp.js")); +var _errors = require("./lib/errors.js"); +var _extractKey = _interopRequireDefault(require("./lib/extractKey.js")); +var _valueToKey = _interopRequireDefault(require("./lib/valueToKey.js")); +var _cloneValueForInsertion = require("./lib/cloneValueForInsertion.js"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +const getEffectiveObjectStore = cursor => { + if (cursor.source instanceof _FDBObjectStore.default) { + return cursor.source; + } + return cursor.source.objectStore; +}; + +// This takes a key range, a list of lower bounds, and a list of upper bounds and combines them all into a single key +// range. It does not handle gt/gte distinctions, because it doesn't really matter much anyway, since for next/prev +// cursor iteration it'd also have to look at values to be precise, which would be complicated. This should get us 99% +// of the way there. +const makeKeyRange = (range, lowers, uppers) => { + // Start with bounds from range + let lower = range !== undefined ? range.lower : undefined; + let upper = range !== undefined ? range.upper : undefined; + + // Augment with values from lowers and uppers + for (const lowerTemp of lowers) { + if (lowerTemp === undefined) { + continue; + } + if (lower === undefined || (0, _cmp.default)(lower, lowerTemp) === 1) { + lower = lowerTemp; + } + } + for (const upperTemp of uppers) { + if (upperTemp === undefined) { + continue; + } + if (upper === undefined || (0, _cmp.default)(upper, upperTemp) === -1) { + upper = upperTemp; + } + } + if (lower !== undefined && upper !== undefined) { + return _FDBKeyRange.default.bound(lower, upper); + } + if (lower !== undefined) { + return _FDBKeyRange.default.lowerBound(lower); + } + if (upper !== undefined) { + return _FDBKeyRange.default.upperBound(upper); + } +}; + +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#cursor +class FDBCursor { + _gotValue = false; + _position = undefined; // Key of previously returned record + _objectStorePosition = undefined; + _keyOnly = false; + _key = undefined; + _primaryKey = undefined; + constructor(source, range, direction = "next", request, keyOnly = false) { + this._range = range; + this._source = source; + this._direction = direction; + this._request = request; + this._keyOnly = keyOnly; + } + + // Read only properties + get source() { + return this._source; + } + set source(val) { + /* For babel */ + } + get request() { + return this._request; + } + set request(val) { + /* For babel */ + } + get direction() { + return this._direction; + } + set direction(val) { + /* For babel */ + } + get key() { + return this._key; + } + set key(val) { + /* For babel */ + } + get primaryKey() { + return this._primaryKey; + } + set primaryKey(val) { + /* For babel */ + } + + // https://w3c.github.io/IndexedDB/#iterate-a-cursor + _iterate(key, primaryKey) { + const sourceIsObjectStore = this.source instanceof _FDBObjectStore.default; + + // Can't use sourceIsObjectStore because TypeScript + const records = this.source instanceof _FDBObjectStore.default ? this.source._rawObjectStore.records : this.source._rawIndex.records; + let foundRecord; + if (this.direction === "next") { + const range = makeKeyRange(this._range, [key, this._position], []); + for (const record of records.values(range)) { + const cmpResultKey = key !== undefined ? (0, _cmp.default)(record.key, key) : undefined; + const cmpResultPosition = this._position !== undefined ? (0, _cmp.default)(record.key, this._position) : undefined; + if (key !== undefined) { + if (cmpResultKey === -1) { + continue; + } + } + if (primaryKey !== undefined) { + if (cmpResultKey === -1) { + continue; + } + const cmpResultPrimaryKey = (0, _cmp.default)(record.value, primaryKey); + if (cmpResultKey === 0 && cmpResultPrimaryKey === -1) { + continue; + } + } + if (this._position !== undefined && sourceIsObjectStore) { + if (cmpResultPosition !== 1) { + continue; + } + } + if (this._position !== undefined && !sourceIsObjectStore) { + if (cmpResultPosition === -1) { + continue; + } + if (cmpResultPosition === 0 && (0, _cmp.default)(record.value, this._objectStorePosition) !== 1) { + continue; + } + } + if (this._range !== undefined) { + if (!this._range.includes(record.key)) { + continue; + } + } + foundRecord = record; + break; + } + } else if (this.direction === "nextunique") { + // This could be done without iterating, if the range was defined slightly better (to handle gt/gte cases). + // But the performance difference should be small, and that wouldn't work anyway for directions where the + // value needs to be used (like next and prev). + const range = makeKeyRange(this._range, [key, this._position], []); + for (const record of records.values(range)) { + if (key !== undefined) { + if ((0, _cmp.default)(record.key, key) === -1) { + continue; + } + } + if (this._position !== undefined) { + if ((0, _cmp.default)(record.key, this._position) !== 1) { + continue; + } + } + if (this._range !== undefined) { + if (!this._range.includes(record.key)) { + continue; + } + } + foundRecord = record; + break; + } + } else if (this.direction === "prev") { + const range = makeKeyRange(this._range, [], [key, this._position]); + for (const record of records.values(range, "prev")) { + const cmpResultKey = key !== undefined ? (0, _cmp.default)(record.key, key) : undefined; + const cmpResultPosition = this._position !== undefined ? (0, _cmp.default)(record.key, this._position) : undefined; + if (key !== undefined) { + if (cmpResultKey === 1) { + continue; + } + } + if (primaryKey !== undefined) { + if (cmpResultKey === 1) { + continue; + } + const cmpResultPrimaryKey = (0, _cmp.default)(record.value, primaryKey); + if (cmpResultKey === 0 && cmpResultPrimaryKey === 1) { + continue; + } + } + if (this._position !== undefined && sourceIsObjectStore) { + if (cmpResultPosition !== -1) { + continue; + } + } + if (this._position !== undefined && !sourceIsObjectStore) { + if (cmpResultPosition === 1) { + continue; + } + if (cmpResultPosition === 0 && (0, _cmp.default)(record.value, this._objectStorePosition) !== -1) { + continue; + } + } + if (this._range !== undefined) { + if (!this._range.includes(record.key)) { + continue; + } + } + foundRecord = record; + break; + } + } else if (this.direction === "prevunique") { + let tempRecord; + const range = makeKeyRange(this._range, [], [key, this._position]); + for (const record of records.values(range, "prev")) { + if (key !== undefined) { + if ((0, _cmp.default)(record.key, key) === 1) { + continue; + } + } + if (this._position !== undefined) { + if ((0, _cmp.default)(record.key, this._position) !== -1) { + continue; + } + } + if (this._range !== undefined) { + if (!this._range.includes(record.key)) { + continue; + } + } + tempRecord = record; + break; + } + if (tempRecord) { + foundRecord = records.get(tempRecord.key); + } + } + let result; + if (!foundRecord) { + this._key = undefined; + if (!sourceIsObjectStore) { + this._objectStorePosition = undefined; + } + + // "this instanceof FDBCursorWithValue" would be better and not require (this as any), but causes runtime + // error due to circular dependency. + if (!this._keyOnly && this.toString() === "[object IDBCursorWithValue]") { + this.value = undefined; + } + result = null; + } else { + this._position = foundRecord.key; + if (!sourceIsObjectStore) { + this._objectStorePosition = foundRecord.value; + } + this._key = foundRecord.key; + if (sourceIsObjectStore) { + this._primaryKey = structuredClone(foundRecord.key); + if (!this._keyOnly && this.toString() === "[object IDBCursorWithValue]") { + this.value = structuredClone(foundRecord.value); + } + } else { + this._primaryKey = structuredClone(foundRecord.value); + if (!this._keyOnly && this.toString() === "[object IDBCursorWithValue]") { + if (this.source instanceof _FDBObjectStore.default) { + // Can't use sourceIsObjectStore because TypeScript + throw new Error("This should never happen"); + } + const value = this.source.objectStore._rawObjectStore.getValue(foundRecord.value); + this.value = structuredClone(value); + } + } + this._gotValue = true; + // eslint-disable-next-line @typescript-eslint/no-this-alias + result = this; + } + return result; + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBCursor-update-IDBRequest-any-value + update(value) { + if (value === undefined) { + throw new TypeError(); + } + const effectiveObjectStore = getEffectiveObjectStore(this); + const effectiveKey = Object.hasOwn(this.source, "_rawIndex") ? this.primaryKey : this._position; + const transaction = effectiveObjectStore.transaction; + if (transaction._state !== "active") { + throw new _errors.TransactionInactiveError(); + } + if (transaction.mode === "readonly") { + throw new _errors.ReadOnlyError(); + } + if (effectiveObjectStore._rawObjectStore.deleted) { + throw new _errors.InvalidStateError(); + } + if (!(this.source instanceof _FDBObjectStore.default) && this.source._rawIndex.deleted) { + throw new _errors.InvalidStateError(); + } + if (!this._gotValue || !Object.hasOwn(this, "value")) { + throw new _errors.InvalidStateError(); + } + const clone = (0, _cloneValueForInsertion.cloneValueForInsertion)(value, transaction); + if (effectiveObjectStore.keyPath !== null) { + let tempKey; + try { + tempKey = (0, _extractKey.default)(effectiveObjectStore.keyPath, clone).key; + } catch (err) { + /* Handled immediately below */ + } + if ((0, _cmp.default)(tempKey, effectiveKey) !== 0) { + throw new _errors.DataError(); + } + } + const record = { + key: effectiveKey, + value: clone + }; + return transaction._execRequestAsync({ + operation: effectiveObjectStore._rawObjectStore.storeRecord.bind(effectiveObjectStore._rawObjectStore, record, false, transaction._rollbackLog), + source: this + }); + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBCursor-advance-void-unsigned-long-count + advance(count) { + if (!Number.isInteger(count) || count <= 0) { + throw new TypeError(); + } + const effectiveObjectStore = getEffectiveObjectStore(this); + const transaction = effectiveObjectStore.transaction; + if (transaction._state !== "active") { + throw new _errors.TransactionInactiveError(); + } + if (effectiveObjectStore._rawObjectStore.deleted) { + throw new _errors.InvalidStateError(); + } + if (!(this.source instanceof _FDBObjectStore.default) && this.source._rawIndex.deleted) { + throw new _errors.InvalidStateError(); + } + if (!this._gotValue) { + throw new _errors.InvalidStateError(); + } + if (this._request) { + this._request.readyState = "pending"; + } + transaction._execRequestAsync({ + operation: () => { + let result; + for (let i = 0; i < count; i++) { + result = this._iterate(); + + // Not sure why this is needed + if (!result) { + break; + } + } + return result; + }, + request: this._request, + source: this.source + }); + this._gotValue = false; + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBCursor-continue-void-any-key + continue(key) { + const effectiveObjectStore = getEffectiveObjectStore(this); + const transaction = effectiveObjectStore.transaction; + if (transaction._state !== "active") { + throw new _errors.TransactionInactiveError(); + } + if (effectiveObjectStore._rawObjectStore.deleted) { + throw new _errors.InvalidStateError(); + } + if (!(this.source instanceof _FDBObjectStore.default) && this.source._rawIndex.deleted) { + throw new _errors.InvalidStateError(); + } + if (!this._gotValue) { + throw new _errors.InvalidStateError(); + } + if (key !== undefined) { + key = (0, _valueToKey.default)(key); + const cmpResult = (0, _cmp.default)(key, this._position); + if (cmpResult <= 0 && (this.direction === "next" || this.direction === "nextunique") || cmpResult >= 0 && (this.direction === "prev" || this.direction === "prevunique")) { + throw new _errors.DataError(); + } + } + if (this._request) { + this._request.readyState = "pending"; + } + transaction._execRequestAsync({ + operation: this._iterate.bind(this, key), + request: this._request, + source: this.source + }); + this._gotValue = false; + } + + // hthttps://w3c.github.io/IndexedDB/#dom-idbcursor-continueprimarykey + continuePrimaryKey(key, primaryKey) { + const effectiveObjectStore = getEffectiveObjectStore(this); + const transaction = effectiveObjectStore.transaction; + if (transaction._state !== "active") { + throw new _errors.TransactionInactiveError(); + } + if (effectiveObjectStore._rawObjectStore.deleted) { + throw new _errors.InvalidStateError(); + } + if (!(this.source instanceof _FDBObjectStore.default) && this.source._rawIndex.deleted) { + throw new _errors.InvalidStateError(); + } + if (this.source instanceof _FDBObjectStore.default || this.direction !== "next" && this.direction !== "prev") { + throw new _errors.InvalidAccessError(); + } + if (!this._gotValue) { + throw new _errors.InvalidStateError(); + } + + // Not sure about this + if (key === undefined || primaryKey === undefined) { + throw new _errors.DataError(); + } + key = (0, _valueToKey.default)(key); + const cmpResult = (0, _cmp.default)(key, this._position); + if (cmpResult === -1 && this.direction === "next" || cmpResult === 1 && this.direction === "prev") { + throw new _errors.DataError(); + } + const cmpResult2 = (0, _cmp.default)(primaryKey, this._objectStorePosition); + if (cmpResult === 0) { + if (cmpResult2 <= 0 && this.direction === "next" || cmpResult2 >= 0 && this.direction === "prev") { + throw new _errors.DataError(); + } + } + if (this._request) { + this._request.readyState = "pending"; + } + transaction._execRequestAsync({ + operation: this._iterate.bind(this, key, primaryKey), + request: this._request, + source: this.source + }); + this._gotValue = false; + } + delete() { + const effectiveObjectStore = getEffectiveObjectStore(this); + const effectiveKey = Object.hasOwn(this.source, "_rawIndex") ? this.primaryKey : this._position; + const transaction = effectiveObjectStore.transaction; + if (transaction._state !== "active") { + throw new _errors.TransactionInactiveError(); + } + if (transaction.mode === "readonly") { + throw new _errors.ReadOnlyError(); + } + if (effectiveObjectStore._rawObjectStore.deleted) { + throw new _errors.InvalidStateError(); + } + if (!(this.source instanceof _FDBObjectStore.default) && this.source._rawIndex.deleted) { + throw new _errors.InvalidStateError(); + } + if (!this._gotValue || !Object.hasOwn(this, "value")) { + throw new _errors.InvalidStateError(); + } + return transaction._execRequestAsync({ + operation: effectiveObjectStore._rawObjectStore.deleteRecord.bind(effectiveObjectStore._rawObjectStore, effectiveKey, transaction._rollbackLog), + source: this + }); + } + get [Symbol.toStringTag]() { + return "IDBCursor"; + } +} +var _default = exports.default = FDBCursor; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/FDBCursorWithValue.js b/node_modules/fake-indexeddb/build/cjs/FDBCursorWithValue.js new file mode 100644 index 0000000000000000000000000000000000000000..8af98ed0ecbff5c6af5df1c7a9094b415b998dfd --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/FDBCursorWithValue.js @@ -0,0 +1,19 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _FDBCursor = _interopRequireDefault(require("./FDBCursor.js")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +class FDBCursorWithValue extends _FDBCursor.default { + value = undefined; + constructor(source, range, direction, request) { + super(source, range, direction, request); + } + get [Symbol.toStringTag]() { + return "IDBCursorWithValue"; + } +} +var _default = exports.default = FDBCursorWithValue; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/FDBDatabase.js b/node_modules/fake-indexeddb/build/cjs/FDBDatabase.js new file mode 100644 index 0000000000000000000000000000000000000000..847f42c59122db3a1eed830ca52f08b8efffdce1 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/FDBDatabase.js @@ -0,0 +1,179 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _FDBTransaction = _interopRequireDefault(require("./FDBTransaction.js")); +var _errors = require("./lib/errors.js"); +var _FakeDOMStringList = _interopRequireDefault(require("./lib/FakeDOMStringList.js")); +var _FakeEventTarget = _interopRequireDefault(require("./lib/FakeEventTarget.js")); +var _ObjectStore = _interopRequireDefault(require("./lib/ObjectStore.js")); +var _validateKeyPath = _interopRequireDefault(require("./lib/validateKeyPath.js")); +var _closeConnection = _interopRequireDefault(require("./lib/closeConnection.js")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +// Common first 3 steps of https://www.w3.org/TR/IndexedDB/#dom-idbdatabase-createobjectstore and https://www.w3.org/TR/IndexedDB/#dom-idbdatabase-deleteobjectstore +const confirmActiveVersionchangeTransaction = database => { + // Let transaction be database’s upgrade transaction if it is not null, or throw an "InvalidStateError" DOMException otherwise. + let transaction; + if (database._runningVersionchangeTransaction) { + // Find the latest versionchange transaction + transaction = database._rawDatabase.transactions.findLast(tx => { + return tx.mode === "versionchange"; + }); + } + if (!transaction) { + throw new _errors.InvalidStateError(); + } + + // If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException. + if (transaction._state !== "active") { + throw new _errors.TransactionInactiveError(); + } + return transaction; +}; + +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#database-interface +class FDBDatabase extends _FakeEventTarget.default { + _closePending = false; + _closed = false; + _runningVersionchangeTransaction = false; + constructor(rawDatabase) { + super(); + this._rawDatabase = rawDatabase; + this._rawDatabase.connections.push(this); + this.name = rawDatabase.name; + this.version = rawDatabase.version; + this.objectStoreNames = new _FakeDOMStringList.default(...Array.from(rawDatabase.rawObjectStores.keys()).sort()); + } + + // http://w3c.github.io/IndexedDB/#dom-idbdatabase-createobjectstore + createObjectStore(name, options = {}) { + if (name === undefined) { + throw new TypeError(); + } + const transaction = confirmActiveVersionchangeTransaction(this); + const keyPath = options !== null && options.keyPath !== undefined ? options.keyPath : null; + const autoIncrement = options !== null && options.autoIncrement !== undefined ? options.autoIncrement : false; + if (keyPath !== null) { + (0, _validateKeyPath.default)(keyPath); + } + if (this._rawDatabase.rawObjectStores.has(name)) { + throw new _errors.ConstraintError(); + } + if (autoIncrement && (keyPath === "" || Array.isArray(keyPath))) { + throw new _errors.InvalidAccessError(); + } + + // Save for rollbackLog + const objectStoreNames = [...this.objectStoreNames]; + const transactionObjectStoreNames = [...transaction.objectStoreNames]; + const rawObjectStore = new _ObjectStore.default(this._rawDatabase, name, keyPath, autoIncrement); + this.objectStoreNames._push(name); + this.objectStoreNames._sort(); + transaction._scope.add(name); + transaction._createdObjectStores.add(rawObjectStore); + this._rawDatabase.rawObjectStores.set(name, rawObjectStore); + transaction.objectStoreNames = new _FakeDOMStringList.default(...this.objectStoreNames); + transaction._rollbackLog.push(() => { + rawObjectStore.deleted = true; + this.objectStoreNames = new _FakeDOMStringList.default(...objectStoreNames); + transaction.objectStoreNames = new _FakeDOMStringList.default(...transactionObjectStoreNames); + transaction._scope.delete(rawObjectStore.name); + this._rawDatabase.rawObjectStores.delete(rawObjectStore.name); + }); + return transaction.objectStore(name); + } + + // https://www.w3.org/TR/IndexedDB/#dom-idbdatabase-deleteobjectstore + deleteObjectStore(name) { + if (name === undefined) { + throw new TypeError(); + } + const transaction = confirmActiveVersionchangeTransaction(this); + + // Let store be the object store named name in database, or throw a "NotFoundError" DOMException if none. + const store = this._rawDatabase.rawObjectStores.get(name); + if (store === undefined) { + throw new _errors.NotFoundError(); + } + + // Remove store from this’s object store set. + // This method synchronously modifies the objectStoreNames property on the IDBDatabase instance on which it was called. + this.objectStoreNames = new _FakeDOMStringList.default(...Array.from(this.objectStoreNames).filter(objectStoreName => { + return objectStoreName !== name; + })); + transaction.objectStoreNames = new _FakeDOMStringList.default(...this.objectStoreNames); + + // If there is an object store handle associated with store and transaction, remove all entries from its index set. + const objectStore = transaction._objectStoresCache.get(name); + let prevIndexNames; + if (objectStore) { + prevIndexNames = [...objectStore.indexNames]; + objectStore.indexNames = new _FakeDOMStringList.default(); + } + transaction._rollbackLog.push(() => { + store.deleted = false; + this._rawDatabase.rawObjectStores.set(store.name, store); + this.objectStoreNames._push(store.name); + transaction.objectStoreNames._push(store.name); + this.objectStoreNames._sort(); + if (objectStore && prevIndexNames) { + objectStore.indexNames = new _FakeDOMStringList.default(...prevIndexNames); + } + }); + + // Destroy store. + store.deleted = true; + this._rawDatabase.rawObjectStores.delete(name); + transaction._objectStoresCache.delete(name); + } + transaction(storeNames, mode, options) { + mode = mode !== undefined ? mode : "readonly"; + if (mode !== "readonly" && mode !== "readwrite" && mode !== "versionchange") { + throw new TypeError("Invalid mode: " + mode); + } + const hasActiveVersionchange = this._rawDatabase.transactions.some(transaction => { + return transaction._state === "active" && transaction.mode === "versionchange" && transaction.db === this; + }); + if (hasActiveVersionchange) { + throw new _errors.InvalidStateError(); + } + if (this._closePending) { + throw new _errors.InvalidStateError(); + } + if (!Array.isArray(storeNames)) { + storeNames = [storeNames]; + } + if (storeNames.length === 0 && mode !== "versionchange") { + throw new _errors.InvalidAccessError(); + } + for (const storeName of storeNames) { + if (!this.objectStoreNames.contains(storeName)) { + throw new _errors.NotFoundError("No objectStore named " + storeName + " in this database"); + } + } + + // the actual algo is more complex but this passes the IDB tests: https://webidl.spec.whatwg.org/#es-dictionary + const durability = options?.durability ?? "default"; + // invalid enums throw a TypeError: https://webidl.spec.whatwg.org/#es-enumeration + if (durability !== "default" && durability !== "strict" && durability !== "relaxed") { + throw new TypeError( + // based on Firefox's error message + `'${durability}' (value of 'durability' member of IDBTransactionOptions) ` + `is not a valid value for enumeration IDBTransactionDurability`); + } + const tx = new _FDBTransaction.default(storeNames, mode, durability, this); + this._rawDatabase.transactions.push(tx); + this._rawDatabase.processTransactions(); // See if can start right away (async) + + return tx; + } + close() { + (0, _closeConnection.default)(this); + } + get [Symbol.toStringTag]() { + return "IDBDatabase"; + } +} +var _default = exports.default = FDBDatabase; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/FDBFactory.js b/node_modules/fake-indexeddb/build/cjs/FDBFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..506b1907583d029b620be2acf16223923b54b5ef --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/FDBFactory.js @@ -0,0 +1,414 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _FDBDatabase = _interopRequireDefault(require("./FDBDatabase.js")); +var _FDBOpenDBRequest = _interopRequireDefault(require("./FDBOpenDBRequest.js")); +var _FDBVersionChangeEvent = _interopRequireDefault(require("./FDBVersionChangeEvent.js")); +var _cmp = _interopRequireDefault(require("./lib/cmp.js")); +var _Database = _interopRequireDefault(require("./lib/Database.js")); +var _enforceRange = _interopRequireDefault(require("./lib/enforceRange.js")); +var _errors = require("./lib/errors.js"); +var _FakeEvent = _interopRequireDefault(require("./lib/FakeEvent.js")); +var _scheduling = require("./lib/scheduling.js"); +var _validateRequiredArguments = require("./lib/validateRequiredArguments.js"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +// https://w3c.github.io/IndexedDB/#connection-queue +const runTaskInConnectionQueue = (connectionQueues, name, task) => { + // Let queue be the connection queue for storageKey and name. + // (note FakeIndexedDB does not support storageKeys currently) + // Add request to queue. + // Wait until all previous requests in queue have been processed. + const queue = connectionQueues.get(name) ?? Promise.resolve(); + connectionQueues.set(name, queue.then(task)); +}; +const waitForOthersClosedDelete = (databases, name, openDatabases, cb) => { + const anyOpen = openDatabases.some(openDatabase2 => { + return !openDatabase2._closed && !openDatabase2._closePending; + }); + if (anyOpen) { + (0, _scheduling.queueTask)(() => waitForOthersClosedDelete(databases, name, openDatabases, cb)); + return; + } + databases.delete(name); + cb(null); +}; + +// https://w3c.github.io/IndexedDB/#delete-a-database +const deleteDatabase = (databases, connectionQueues, name, request, cb) => { + const deleteDBTask = () => { + return new Promise(resolve => { + const db = databases.get(name); + const oldVersion = db !== undefined ? db.version : 0; + const onComplete = err => { + try { + if (err) { + cb(err); + } else { + cb(null, oldVersion); + } + } finally { + resolve(); + } + }; + try { + const db = databases.get(name); + if (db === undefined) { + onComplete(null); + return; + } + + // Let openConnections be the set of all connections associated with db. + const openConnections = db.connections.filter(connection => { + return !connection._closed; + }); + + // For each entry of openConnections that does not have its close pending flag set to true, queue a + // database task to fire a version change event named versionchange at entry with db’s version and null. + for (const openDatabase2 of openConnections) { + if (!openDatabase2._closePending) { + (0, _scheduling.queueTask)(() => { + const event = new _FDBVersionChangeEvent.default("versionchange", { + newVersion: null, + oldVersion: db.version + }); + openDatabase2.dispatchEvent(event); + }); + } + } + + // Wait for all of the events to be fired. (i.e. queue a task) + (0, _scheduling.queueTask)(() => { + // If any of the connections in openConnections are still not closed, queue a database task to + // fire a version change event named blocked at request with db’s version and null. + + const anyOpen = openConnections.some(openDatabase3 => { + return !openDatabase3._closed && !openDatabase3._closePending; + }); + + // If any of the connections in openConnections are still not closed, queue a database task to + // fire a version change event named blocked at request with db’s version and null. + if (anyOpen) { + (0, _scheduling.queueTask)(() => { + const event = new _FDBVersionChangeEvent.default("blocked", { + newVersion: null, + oldVersion: db.version + }); + request.dispatchEvent(event); + }); + } + + // Wait until all connections in openConnections are closed. + waitForOthersClosedDelete(databases, name, openConnections, onComplete); + }); + } catch (err) { + onComplete(err); + } + }); + }; + runTaskInConnectionQueue(connectionQueues, name, deleteDBTask); +}; + +// https://w3c.github.io/IndexedDB/#ref-for-database-version%E2%91%A0%E2%91%A2 +const runVersionchangeTransaction = (connection, version, request, cb) => { + connection._runningVersionchangeTransaction = true; + const oldVersion = connection._oldVersion = connection.version; + + // Let openConnections be the set of all connections, except connection, associated with db. + const openConnections = connection._rawDatabase.connections.filter(otherDatabase => { + return connection !== otherDatabase; + }); + + // For each entry of openConnections that does not have its close pending flag set to true, queue a + // database task to fire a version change event named versionchange at entry with db’s version and version. + for (const openDatabase2 of openConnections) { + if (!openDatabase2._closed && !openDatabase2._closePending) { + (0, _scheduling.queueTask)(() => { + const event = new _FDBVersionChangeEvent.default("versionchange", { + newVersion: version, + oldVersion + }); + openDatabase2.dispatchEvent(event); + }); + } + } + + // Wait for all of the events to be fired. + // (i.e. queue a task) + (0, _scheduling.queueTask)(() => { + const anyOpen = openConnections.some(openDatabase3 => { + return !openDatabase3._closed && !openDatabase3._closePending; + }); + + // If any of the connections in openConnections are still not closed, queue a database task to fire a version change event named blocked at request with db’s version and version. + if (anyOpen) { + (0, _scheduling.queueTask)(() => { + const event = new _FDBVersionChangeEvent.default("blocked", { + newVersion: version, + oldVersion + }); + request.dispatchEvent(event); + }); + } + + // Wait until all connections in openConnections are closed. + const waitForOthersClosed = () => { + const anyOpen2 = openConnections.some(openDatabase2 => { + return !openDatabase2._closed && !openDatabase2._closePending; + }); + if (anyOpen2) { + (0, _scheduling.queueTask)(waitForOthersClosed); + return; + } + + // Set the version of database to version. This change is considered part of the transaction, and so if the + // transaction is aborted, this change is reverted. + connection._rawDatabase.version = version; + connection.version = version; + + // Get rid of this setImmediate? + const transaction = connection.transaction(Array.from(connection.objectStoreNames), "versionchange"); + + // associate the transaction with the open request for later lookup + transaction._openRequest = request; + + // https://w3c.github.io/IndexedDB/#upgrade-a-database + // Set request’s result to connection. + request.result = connection; + // Set request’s done flag to true. + request.readyState = "done"; + // Set request’s transaction to transaction. + request.transaction = transaction; + transaction._rollbackLog.push(() => { + connection._rawDatabase.version = oldVersion; + connection.version = oldVersion; + }); + + // Set transaction’s state to active. + transaction._state = "active"; + + // Let didThrow be the result of firing a version change event named upgradeneeded at request with old version and version. + const event = new _FDBVersionChangeEvent.default("upgradeneeded", { + newVersion: version, + oldVersion + }); + let didThrow = false; + try { + request.dispatchEvent(event); + } catch (_err) { + didThrow = true; + } + const concludeUpgrade = () => { + // If transaction’s state is active, then: + if (transaction._state === "active") { + // Set transaction’s state to inactive. + transaction._state = "inactive"; + if (didThrow) { + // If didThrow is true, run abort a transaction with transaction and a newly created "AbortError" DOMException. + transaction._abort("AbortError"); + } + } + }; + + // The "upgrade a database" steps are supposed to run as a database task on the database access task source + // (i.e. off the main thread), but since we're actually running on the main thread, we have to be tricky: + // 1. If any `upgradeneeded` event handlers errored, abort synchronously + // 2. Else yield to allow any microtasks to run in response to that event + if (didThrow) { + concludeUpgrade(); + } else { + (0, _scheduling.queueTask)(concludeUpgrade); + } + transaction._prioritizedListeners.set("error", () => { + connection._runningVersionchangeTransaction = false; + connection._oldVersion = undefined; + // throw arguments[0].target.error; + // console.log("error in versionchange transaction - not sure if anything needs to be done here", e.target.error.name); + }); + transaction._prioritizedListeners.set("abort", () => { + connection._runningVersionchangeTransaction = false; + connection._oldVersion = undefined; + (0, _scheduling.queueTask)(() => { + // Reset transaction in a tick after onabort (upgrade-transaction-lifecycle-user-aborted.any) + request.transaction = null; + cb(new _errors.AbortError()); + }); + }); + transaction._prioritizedListeners.set("complete", () => { + connection._runningVersionchangeTransaction = false; + connection._oldVersion = undefined; + // Let other complete event handlers run before continuing + (0, _scheduling.queueTask)(() => { + // Reset transaction in a tick after oncomplete (upgrade-transaction-lifecycle-committed.any.js) + request.transaction = null; + if (connection._closePending) { + cb(new _errors.AbortError()); + } else { + cb(null); + } + }); + }); + }; + waitForOthersClosed(); + }); +}; + +// https://w3c.github.io/IndexedDB/#opening +const openDatabase = (databases, connectionQueues, name, version, request, cb) => { + const openDBTask = () => { + return new Promise(resolve => { + const onComplete = err => { + try { + if (err) { + // DO THIS HERE: ensure that connection is closed by running the steps for closing a database connection before these + // steps are aborted. + cb(err); + } else { + cb(null, connection); + } + } finally { + resolve(); + } + }; + + // Let db be the database named name in storageKey, or null otherwise. + let db = databases.get(name); + if (db === undefined) { + // If db is null, let db be a new database with name `name`, version 0 (zero), and with no object stores. + db = new _Database.default(name, 0); + databases.set(name, db); + } + + // If version is undefined, let version be 1 if db is null, or db’s version otherwise. + if (version === undefined) { + version = db.version !== 0 ? db.version : 1; + } + + // If db’s version is greater than version, return a newly created "VersionError" DOMException and abort these steps. + if (db.version > version) { + return onComplete(new _errors.VersionError()); + } + + // Let connection be a new connection to db. + const connection = new _FDBDatabase.default(db); + + // If db’s version is less than version, then: + if (db.version < version) { + // (run a version change transaction and resolve so that the next promise in the queue will execute) + runVersionchangeTransaction(connection, version, request, err => { + onComplete(err); + }); + } else { + onComplete(null); + } + }); + }; + runTaskInConnectionQueue(connectionQueues, name, openDBTask); +}; +class FDBFactory { + _databases = new Map(); + // https://w3c.github.io/IndexedDB/#connection-queue + _connectionQueues = new Map(); // promise chain as lightweight FIFO task queue + + // https://w3c.github.io/IndexedDB/#dom-idbfactory-cmp + cmp(first, second) { + (0, _validateRequiredArguments.validateRequiredArguments)(arguments.length, 2, "IDBFactory.cmp"); + return (0, _cmp.default)(first, second); + } + + // https://w3c.github.io/IndexedDB/#dom-idbfactory-deletedatabase + deleteDatabase(name) { + (0, _validateRequiredArguments.validateRequiredArguments)(arguments.length, 1, "IDBFactory.deleteDatabase"); + const request = new _FDBOpenDBRequest.default(); + request.source = null; + (0, _scheduling.queueTask)(() => { + deleteDatabase(this._databases, this._connectionQueues, name, request, (err, oldVersion) => { + if (err) { + request.error = new DOMException(err.message, err.name); + request.readyState = "done"; + const event = new _FakeEvent.default("error", { + bubbles: true, + cancelable: true + }); + event.eventPath = []; + request.dispatchEvent(event); + return; + } + request.result = undefined; + request.readyState = "done"; + const event2 = new _FDBVersionChangeEvent.default("success", { + newVersion: null, + oldVersion + }); + request.dispatchEvent(event2); + }); + }); + return request; + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBFactory-open-IDBOpenDBRequest-DOMString-name-unsigned-long-long-version + open(name, version) { + (0, _validateRequiredArguments.validateRequiredArguments)(arguments.length, 1, "IDBFactory.open"); + if (arguments.length > 1 && version !== undefined) { + // Based on spec, not sure why "MAX_SAFE_INTEGER" instead of "unsigned long long", but it's needed to pass + // tests + version = (0, _enforceRange.default)(version, "MAX_SAFE_INTEGER"); + } + if (version === 0) { + throw new TypeError("Database version cannot be 0"); + } + const request = new _FDBOpenDBRequest.default(); + request.source = null; + (0, _scheduling.queueTask)(() => { + openDatabase(this._databases, this._connectionQueues, name, version, request, (err, connection) => { + if (err) { + request.result = undefined; + request.readyState = "done"; + request.error = new DOMException(err.message, err.name); + const event = new _FakeEvent.default("error", { + bubbles: true, + cancelable: true + }); + event.eventPath = []; + request.dispatchEvent(event); + return; + } + request.result = connection; + request.readyState = "done"; + const event2 = new _FakeEvent.default("success"); + event2.eventPath = []; + request.dispatchEvent(event2); + }); + }); + return request; + } + + // https://w3c.github.io/IndexedDB/#dom-idbfactory-databases + databases() { + return Promise.resolve(Array.from(this._databases.entries(), ([name, database]) => { + const activeVersionChangeConnection = database.connections.find(connection => connection._runningVersionchangeTransaction); + // If a versionchange is in progress, report the old version. See `get-databases.any.js` test: + // "The result of databases() should contain the versions of databases at the time of calling, + // regardless of versionchange transactions currently running." + const version = activeVersionChangeConnection ? activeVersionChangeConnection._oldVersion : database.version; + return { + name, + version + }; + }).filter(({ + version + }) => { + // Ignore newly-created DBs with active versionchange transactions. See `get-databases.any.js` test: + // "The result of databases() should be only those databases which have been created at the + // time of calling, regardless of versionchange transactions currently running." + return version > 0; + })); + } + get [Symbol.toStringTag]() { + return "IDBFactory"; + } +} +var _default = exports.default = FDBFactory; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/FDBIndex.js b/node_modules/fake-indexeddb/build/cjs/FDBIndex.js new file mode 100644 index 0000000000000000000000000000000000000000..5678fbcb1b3e63862f63662231d04d9cba3962c4 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/FDBIndex.js @@ -0,0 +1,217 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _FDBCursor = _interopRequireDefault(require("./FDBCursor.js")); +var _FDBCursorWithValue = _interopRequireDefault(require("./FDBCursorWithValue.js")); +var _FDBKeyRange = _interopRequireDefault(require("./FDBKeyRange.js")); +var _FDBRequest = _interopRequireDefault(require("./FDBRequest.js")); +var _errors = require("./lib/errors.js"); +var _FakeDOMStringList = _interopRequireDefault(require("./lib/FakeDOMStringList.js")); +var _valueToKey = _interopRequireDefault(require("./lib/valueToKey.js")); +var _valueToKeyRange = _interopRequireDefault(require("./lib/valueToKeyRange.js")); +var _getKeyPath = require("./lib/getKeyPath.js"); +var _extractGetAllOptions = _interopRequireDefault(require("./lib/extractGetAllOptions.js")); +var _enforceRange = _interopRequireDefault(require("./lib/enforceRange.js")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +const confirmActiveTransaction = index => { + if (index._rawIndex.deleted || index.objectStore._rawObjectStore.deleted) { + throw new _errors.InvalidStateError(); + } + if (index.objectStore.transaction._state !== "active") { + throw new _errors.TransactionInactiveError(); + } +}; + +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#idl-def-IDBIndex +class FDBIndex { + constructor(objectStore, rawIndex) { + this._rawIndex = rawIndex; + this._name = rawIndex.name; + this.objectStore = objectStore; + this.keyPath = (0, _getKeyPath.getKeyPath)(rawIndex.keyPath); + this.multiEntry = rawIndex.multiEntry; + this.unique = rawIndex.unique; + } + get name() { + return this._name; + } + + // https://w3c.github.io/IndexedDB/#dom-idbindex-name + set name(name) { + const transaction = this.objectStore.transaction; + if (!transaction.db._runningVersionchangeTransaction) { + throw transaction._state === "active" ? new _errors.InvalidStateError() : new _errors.TransactionInactiveError(); + } + if (transaction._state !== "active") { + throw new _errors.TransactionInactiveError(); + } + if (this._rawIndex.deleted || this.objectStore._rawObjectStore.deleted) { + throw new _errors.InvalidStateError(); + } + name = String(name); + if (name === this._name) { + return; + } + if (this.objectStore.indexNames.contains(name)) { + throw new _errors.ConstraintError(); + } + const oldName = this._name; + const oldIndexNames = [...this.objectStore.indexNames]; + this._name = name; + this._rawIndex.name = name; + this.objectStore._indexesCache.delete(oldName); + this.objectStore._indexesCache.set(name, this); + this.objectStore._rawObjectStore.rawIndexes.delete(oldName); + this.objectStore._rawObjectStore.rawIndexes.set(name, this._rawIndex); + this.objectStore.indexNames = new _FakeDOMStringList.default(...Array.from(this.objectStore._rawObjectStore.rawIndexes.keys()).filter(indexName => { + const index = this.objectStore._rawObjectStore.rawIndexes.get(indexName); + return index && !index.deleted; + }).sort()); + + // https://www.w3.org/TR/IndexedDB/#abort-an-upgrade-transaction - "If handle’s index was not newly created during transaction, set handle’s name to its index’s name." + if (!this.objectStore.transaction._createdIndexes.has(this._rawIndex)) { + transaction._rollbackLog.push(() => { + this._name = oldName; + this._rawIndex.name = oldName; + this.objectStore._indexesCache.delete(name); + this.objectStore._indexesCache.set(oldName, this); + this.objectStore._rawObjectStore.rawIndexes.delete(name); + this.objectStore._rawObjectStore.rawIndexes.set(oldName, this._rawIndex); + this.objectStore.indexNames = new _FakeDOMStringList.default(...oldIndexNames); + }); + } + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-openCursor-IDBRequest-any-range-IDBCursorDirection-direction + openCursor(range, direction) { + confirmActiveTransaction(this); + if (range === null) { + range = undefined; + } + if (range !== undefined && !(range instanceof _FDBKeyRange.default)) { + range = _FDBKeyRange.default.only((0, _valueToKey.default)(range)); + } + const request = new _FDBRequest.default(); + request.source = this; + request.transaction = this.objectStore.transaction; + const cursor = new _FDBCursorWithValue.default(this, range, direction, request); + return this.objectStore.transaction._execRequestAsync({ + operation: cursor._iterate.bind(cursor), + request, + source: this + }); + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-openKeyCursor-IDBRequest-any-range-IDBCursorDirection-direction + openKeyCursor(range, direction) { + confirmActiveTransaction(this); + if (range === null) { + range = undefined; + } + if (range !== undefined && !(range instanceof _FDBKeyRange.default)) { + range = _FDBKeyRange.default.only((0, _valueToKey.default)(range)); + } + const request = new _FDBRequest.default(); + request.source = this; + request.transaction = this.objectStore.transaction; + const cursor = new _FDBCursor.default(this, range, direction, request, true); + return this.objectStore.transaction._execRequestAsync({ + operation: cursor._iterate.bind(cursor), + request, + source: this + }); + } + get(key) { + confirmActiveTransaction(this); + if (!(key instanceof _FDBKeyRange.default)) { + key = (0, _valueToKey.default)(key); + } + return this.objectStore.transaction._execRequestAsync({ + operation: this._rawIndex.getValue.bind(this._rawIndex, key), + source: this + }); + } + + // http://w3c.github.io/IndexedDB/#dom-idbindex-getall + getAll(queryOrOptions, count) { + const options = (0, _extractGetAllOptions.default)(queryOrOptions, count, arguments.length); + confirmActiveTransaction(this); + const range = (0, _valueToKeyRange.default)(options.query); + return this.objectStore.transaction._execRequestAsync({ + operation: this._rawIndex.getAllValues.bind(this._rawIndex, range, options.count, options.direction), + source: this + }); + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-getKey-IDBRequest-any-key + getKey(key) { + confirmActiveTransaction(this); + if (!(key instanceof _FDBKeyRange.default)) { + key = (0, _valueToKey.default)(key); + } + return this.objectStore.transaction._execRequestAsync({ + operation: this._rawIndex.getKey.bind(this._rawIndex, key), + source: this + }); + } + + // http://w3c.github.io/IndexedDB/#dom-idbindex-getallkeys + getAllKeys(queryOrOptions, count) { + const options = (0, _extractGetAllOptions.default)(queryOrOptions, count, arguments.length); + confirmActiveTransaction(this); + const range = (0, _valueToKeyRange.default)(options.query); + return this.objectStore.transaction._execRequestAsync({ + operation: this._rawIndex.getAllKeys.bind(this._rawIndex, range, options.count, options.direction), + source: this + }); + } + + // https://www.w3.org/TR/IndexedDB/#dom-idbobjectstore-getallrecords + getAllRecords(options) { + let query; + let count; + let direction; + if (options !== undefined) { + if (options.query !== undefined) { + query = options.query; + } + if (options.count !== undefined) { + count = (0, _enforceRange.default)(options.count, "unsigned long"); + } + if (options.direction !== undefined) { + direction = options.direction; + } + } + confirmActiveTransaction(this); + const range = (0, _valueToKeyRange.default)(query); + return this.objectStore.transaction._execRequestAsync({ + operation: this._rawIndex.getAllRecords.bind(this._rawIndex, range, count, direction), + source: this + }); + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-count-IDBRequest-any-key + count(key) { + confirmActiveTransaction(this); + if (key === null) { + key = undefined; + } + if (key !== undefined && !(key instanceof _FDBKeyRange.default)) { + key = _FDBKeyRange.default.only((0, _valueToKey.default)(key)); + } + return this.objectStore.transaction._execRequestAsync({ + operation: () => { + return this._rawIndex.count(key); + }, + source: this + }); + } + get [Symbol.toStringTag]() { + return "IDBIndex"; + } +} +var _default = exports.default = FDBIndex; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/FDBKeyRange.js b/node_modules/fake-indexeddb/build/cjs/FDBKeyRange.js new file mode 100644 index 0000000000000000000000000000000000000000..a397ab5fcd683b36d9a299a040e07d9db0ea2db9 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/FDBKeyRange.js @@ -0,0 +1,78 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _cmp = _interopRequireDefault(require("./lib/cmp.js")); +var _errors = require("./lib/errors.js"); +var _valueToKey = _interopRequireDefault(require("./lib/valueToKey.js")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#range-concept +class FDBKeyRange { + static only(value) { + if (arguments.length === 0) { + throw new TypeError(); + } + value = (0, _valueToKey.default)(value); + return new FDBKeyRange(value, value, false, false); + } + static lowerBound(lower, open = false) { + if (arguments.length === 0) { + throw new TypeError(); + } + lower = (0, _valueToKey.default)(lower); + return new FDBKeyRange(lower, undefined, open, true); + } + static upperBound(upper, open = false) { + if (arguments.length === 0) { + throw new TypeError(); + } + upper = (0, _valueToKey.default)(upper); + return new FDBKeyRange(undefined, upper, true, open); + } + static bound(lower, upper, lowerOpen = false, upperOpen = false) { + if (arguments.length < 2) { + throw new TypeError(); + } + const cmpResult = (0, _cmp.default)(lower, upper); + if (cmpResult === 1 || cmpResult === 0 && (lowerOpen || upperOpen)) { + throw new _errors.DataError(); + } + lower = (0, _valueToKey.default)(lower); + upper = (0, _valueToKey.default)(upper); + return new FDBKeyRange(lower, upper, lowerOpen, upperOpen); + } + constructor(lower, upper, lowerOpen, upperOpen) { + this.lower = lower; + this.upper = upper; + this.lowerOpen = lowerOpen; + this.upperOpen = upperOpen; + } + + // https://w3c.github.io/IndexedDB/#dom-idbkeyrange-includes + includes(key) { + if (arguments.length === 0) { + throw new TypeError(); + } + key = (0, _valueToKey.default)(key); + if (this.lower !== undefined) { + const cmpResult = (0, _cmp.default)(this.lower, key); + if (cmpResult === 1 || cmpResult === 0 && this.lowerOpen) { + return false; + } + } + if (this.upper !== undefined) { + const cmpResult = (0, _cmp.default)(this.upper, key); + if (cmpResult === -1 || cmpResult === 0 && this.upperOpen) { + return false; + } + } + return true; + } + get [Symbol.toStringTag]() { + return "IDBKeyRange"; + } +} +var _default = exports.default = FDBKeyRange; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/FDBObjectStore.js b/node_modules/fake-indexeddb/build/cjs/FDBObjectStore.js new file mode 100644 index 0000000000000000000000000000000000000000..fed79048399c44bd10fb9cb9e98d8fb1f844bdf9 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/FDBObjectStore.js @@ -0,0 +1,409 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _FDBCursor = _interopRequireDefault(require("./FDBCursor.js")); +var _FDBCursorWithValue = _interopRequireDefault(require("./FDBCursorWithValue.js")); +var _FDBIndex = _interopRequireDefault(require("./FDBIndex.js")); +var _FDBKeyRange = _interopRequireDefault(require("./FDBKeyRange.js")); +var _FDBRequest = _interopRequireDefault(require("./FDBRequest.js")); +var _canInjectKey = _interopRequireDefault(require("./lib/canInjectKey.js")); +var _errors = require("./lib/errors.js"); +var _extractKey = _interopRequireDefault(require("./lib/extractKey.js")); +var _FakeDOMStringList = _interopRequireDefault(require("./lib/FakeDOMStringList.js")); +var _Index = _interopRequireDefault(require("./lib/Index.js")); +var _validateKeyPath = _interopRequireDefault(require("./lib/validateKeyPath.js")); +var _valueToKey = _interopRequireDefault(require("./lib/valueToKey.js")); +var _valueToKeyRange = _interopRequireDefault(require("./lib/valueToKeyRange.js")); +var _getKeyPath = require("./lib/getKeyPath.js"); +var _extractGetAllOptions = _interopRequireDefault(require("./lib/extractGetAllOptions.js")); +var _enforceRange = _interopRequireDefault(require("./lib/enforceRange.js")); +var _cloneValueForInsertion = require("./lib/cloneValueForInsertion.js"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +const confirmActiveTransaction = objectStore => { + if (objectStore._rawObjectStore.deleted) { + throw new _errors.InvalidStateError(); + } + if (objectStore.transaction._state !== "active") { + throw new _errors.TransactionInactiveError(); + } +}; +const buildRecordAddPut = (objectStore, value, key) => { + confirmActiveTransaction(objectStore); + if (objectStore.transaction.mode === "readonly") { + throw new _errors.ReadOnlyError(); + } + if (objectStore.keyPath !== null) { + if (key !== undefined) { + throw new _errors.DataError(); + } + } + const clone = (0, _cloneValueForInsertion.cloneValueForInsertion)(value, objectStore.transaction); + if (objectStore.keyPath !== null) { + const tempKey = (0, _extractKey.default)(objectStore.keyPath, clone); + if (tempKey.type === "found") { + (0, _valueToKey.default)(tempKey.key); + } else { + if (!objectStore._rawObjectStore.keyGenerator) { + throw new _errors.DataError(); + } else if (!(0, _canInjectKey.default)(objectStore.keyPath, clone)) { + throw new _errors.DataError(); + } + } + } + if (objectStore.keyPath === null && objectStore._rawObjectStore.keyGenerator === null && key === undefined) { + throw new _errors.DataError(); + } + if (key !== undefined) { + key = (0, _valueToKey.default)(key); + } + return { + key, + value: clone + }; +}; + +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#object-store +class FDBObjectStore { + _indexesCache = new Map(); + constructor(transaction, rawObjectStore) { + this._rawObjectStore = rawObjectStore; + this._name = rawObjectStore.name; + this.keyPath = (0, _getKeyPath.getKeyPath)(rawObjectStore.keyPath); + this.autoIncrement = rawObjectStore.autoIncrement; + this.transaction = transaction; + this.indexNames = new _FakeDOMStringList.default(...Array.from(rawObjectStore.rawIndexes.keys()).sort()); + } + get name() { + return this._name; + } + + // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-name + set name(name) { + const transaction = this.transaction; + if (!transaction.db._runningVersionchangeTransaction) { + throw transaction._state === "active" ? new _errors.InvalidStateError() : new _errors.TransactionInactiveError(); + } + confirmActiveTransaction(this); + name = String(name); + if (name === this._name) { + return; + } + if (this._rawObjectStore.rawDatabase.rawObjectStores.has(name)) { + throw new _errors.ConstraintError(); + } + const oldName = this._name; + const oldObjectStoreNames = [...transaction.db.objectStoreNames]; + this._name = name; + this._rawObjectStore.name = name; + this.transaction._objectStoresCache.delete(oldName); + this.transaction._objectStoresCache.set(name, this); + this._rawObjectStore.rawDatabase.rawObjectStores.delete(oldName); + this._rawObjectStore.rawDatabase.rawObjectStores.set(name, this._rawObjectStore); + transaction.db.objectStoreNames = new _FakeDOMStringList.default(...Array.from(this._rawObjectStore.rawDatabase.rawObjectStores.keys()).filter(objectStoreName => { + const objectStore = this._rawObjectStore.rawDatabase.rawObjectStores.get(objectStoreName); + return objectStore && !objectStore.deleted; + }).sort()); + const oldScope = new Set(transaction._scope); + const oldTransactionObjectStoreNames = [...transaction.objectStoreNames]; + this.transaction._scope.delete(oldName); + transaction._scope.add(name); + transaction.objectStoreNames = new _FakeDOMStringList.default(...Array.from(transaction._scope).sort()); + + // https://www.w3.org/TR/IndexedDB/#abort-an-upgrade-transaction - "If handle’s object store was not newly created during transaction, set handle’s name to its object store’s name." + if (!this.transaction._createdObjectStores.has(this._rawObjectStore)) { + transaction._rollbackLog.push(() => { + this._name = oldName; + this._rawObjectStore.name = oldName; + this.transaction._objectStoresCache.delete(name); + this.transaction._objectStoresCache.set(oldName, this); + this._rawObjectStore.rawDatabase.rawObjectStores.delete(name); + this._rawObjectStore.rawDatabase.rawObjectStores.set(oldName, this._rawObjectStore); + transaction.db.objectStoreNames = new _FakeDOMStringList.default(...oldObjectStoreNames); + transaction._scope = oldScope; + transaction.objectStoreNames = new _FakeDOMStringList.default(...oldTransactionObjectStoreNames); + }); + } + } + put(value, key) { + if (arguments.length === 0) { + throw new TypeError(); + } + const record = buildRecordAddPut(this, value, key); + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.storeRecord.bind(this._rawObjectStore, record, false, this.transaction._rollbackLog), + source: this + }); + } + add(value, key) { + if (arguments.length === 0) { + throw new TypeError(); + } + const record = buildRecordAddPut(this, value, key); + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.storeRecord.bind(this._rawObjectStore, record, true, this.transaction._rollbackLog), + source: this + }); + } + delete(key) { + if (arguments.length === 0) { + throw new TypeError(); + } + confirmActiveTransaction(this); + if (this.transaction.mode === "readonly") { + throw new _errors.ReadOnlyError(); + } + if (!(key instanceof _FDBKeyRange.default)) { + key = (0, _valueToKey.default)(key); + } + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.deleteRecord.bind(this._rawObjectStore, key, this.transaction._rollbackLog), + source: this + }); + } + get(key) { + if (arguments.length === 0) { + throw new TypeError(); + } + confirmActiveTransaction(this); + if (!(key instanceof _FDBKeyRange.default)) { + key = (0, _valueToKey.default)(key); + } + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.getValue.bind(this._rawObjectStore, key), + source: this + }); + } + + // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-getall + getAll(queryOrOptions, count) { + const options = (0, _extractGetAllOptions.default)(queryOrOptions, count, arguments.length); + confirmActiveTransaction(this); + const range = (0, _valueToKeyRange.default)(options.query); + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.getAllValues.bind(this._rawObjectStore, range, options.count, options.direction), + source: this + }); + } + + // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-getkey + getKey(key) { + if (arguments.length === 0) { + throw new TypeError(); + } + confirmActiveTransaction(this); + if (!(key instanceof _FDBKeyRange.default)) { + key = (0, _valueToKey.default)(key); + } + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.getKey.bind(this._rawObjectStore, key), + source: this + }); + } + + // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-getallkeys + getAllKeys(queryOrOptions, count) { + const options = (0, _extractGetAllOptions.default)(queryOrOptions, count, arguments.length); + confirmActiveTransaction(this); + const range = (0, _valueToKeyRange.default)(options.query); + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.getAllKeys.bind(this._rawObjectStore, range, options.count, options.direction), + source: this + }); + } + + // https://www.w3.org/TR/IndexedDB/#dom-idbobjectstore-getallrecords + getAllRecords(options) { + let query; + let count; + let direction; + if (options !== undefined) { + if (options.query !== undefined) { + query = options.query; + } + if (options.count !== undefined) { + count = (0, _enforceRange.default)(options.count, "unsigned long"); + } + if (options.direction !== undefined) { + direction = options.direction; + } + } + confirmActiveTransaction(this); + const range = (0, _valueToKeyRange.default)(query); + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.getAllRecords.bind(this._rawObjectStore, range, count, direction), + source: this + }); + } + clear() { + confirmActiveTransaction(this); + if (this.transaction.mode === "readonly") { + throw new _errors.ReadOnlyError(); + } + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.clear.bind(this._rawObjectStore, this.transaction._rollbackLog), + source: this + }); + } + openCursor(range, direction) { + confirmActiveTransaction(this); + if (range === null) { + range = undefined; + } + if (range !== undefined && !(range instanceof _FDBKeyRange.default)) { + range = _FDBKeyRange.default.only((0, _valueToKey.default)(range)); + } + const request = new _FDBRequest.default(); + request.source = this; + request.transaction = this.transaction; + const cursor = new _FDBCursorWithValue.default(this, range, direction, request); + return this.transaction._execRequestAsync({ + operation: cursor._iterate.bind(cursor), + request, + source: this + }); + } + openKeyCursor(range, direction) { + confirmActiveTransaction(this); + if (range === null) { + range = undefined; + } + if (range !== undefined && !(range instanceof _FDBKeyRange.default)) { + range = _FDBKeyRange.default.only((0, _valueToKey.default)(range)); + } + const request = new _FDBRequest.default(); + request.source = this; + request.transaction = this.transaction; + const cursor = new _FDBCursor.default(this, range, direction, request, true); + return this.transaction._execRequestAsync({ + operation: cursor._iterate.bind(cursor), + request, + source: this + }); + } + + // tslint:-next-line max-line-length + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBObjectStore-createIndex-IDBIndex-DOMString-name-DOMString-sequence-DOMString--keyPath-IDBIndexParameters-optionalParameters + createIndex(name, keyPath, optionalParameters = {}) { + if (arguments.length < 2) { + throw new TypeError(); + } + const multiEntry = optionalParameters.multiEntry !== undefined ? optionalParameters.multiEntry : false; + const unique = optionalParameters.unique !== undefined ? optionalParameters.unique : false; + if (this.transaction.mode !== "versionchange") { + throw new _errors.InvalidStateError(); + } + confirmActiveTransaction(this); + if (this.indexNames.contains(name)) { + throw new _errors.ConstraintError(); + } + (0, _validateKeyPath.default)(keyPath); + if (Array.isArray(keyPath) && multiEntry) { + throw new _errors.InvalidAccessError(); + } + + // The index that is requested to be created can contain constraints on the data allowed in the index's + // referenced object store, such as requiring uniqueness of the values referenced by the index's keyPath. If the + // referenced object store already contains data which violates these constraints, this MUST NOT cause the + // implementation of createIndex to throw an exception or affect what it returns. The implementation MUST still + // create and return an IDBIndex object. Instead the implementation must queue up an operation to abort the + // "versionchange" transaction which was used for the createIndex call. + + // Save for rollbackLog + const indexNames = [...this.indexNames]; + const index = new _Index.default(this._rawObjectStore, name, keyPath, multiEntry, unique); + this.indexNames._push(name); + this.indexNames._sort(); + this.transaction._createdIndexes.add(index); + this._rawObjectStore.rawIndexes.set(name, index); + index.initialize(this.transaction); // This is async by design + + this.transaction._rollbackLog.push(() => { + index.deleted = true; + this.indexNames = new _FakeDOMStringList.default(...indexNames); + this._rawObjectStore.rawIndexes.delete(index.name); + }); + return new _FDBIndex.default(this, index); + } + + // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-index + index(name) { + if (arguments.length === 0) { + throw new TypeError(); + } + if (this._rawObjectStore.deleted || this.transaction._state === "finished") { + throw new _errors.InvalidStateError(); + } + const index = this._indexesCache.get(name); + if (index !== undefined) { + return index; + } + const rawIndex = this._rawObjectStore.rawIndexes.get(name); + if (!this.indexNames.contains(name) || rawIndex === undefined) { + throw new _errors.NotFoundError(); + } + const index2 = new _FDBIndex.default(this, rawIndex); + this._indexesCache.set(name, index2); + return index2; + } + deleteIndex(name) { + if (arguments.length === 0) { + throw new TypeError(); + } + if (this.transaction.mode !== "versionchange") { + throw new _errors.InvalidStateError(); + } + confirmActiveTransaction(this); + const rawIndex = this._rawObjectStore.rawIndexes.get(name); + if (rawIndex === undefined) { + throw new _errors.NotFoundError(); + } + this.transaction._rollbackLog.push(() => { + rawIndex.deleted = false; + this._rawObjectStore.rawIndexes.set(rawIndex.name, rawIndex); + this.indexNames._push(rawIndex.name); + this.indexNames._sort(); + }); + this.indexNames = new _FakeDOMStringList.default(...Array.from(this.indexNames).filter(indexName => { + return indexName !== name; + })); + rawIndex.deleted = true; // Not sure if this is supposed to happen synchronously + + this.transaction._execRequestAsync({ + operation: () => { + const rawIndex2 = this._rawObjectStore.rawIndexes.get(name); + + // Hack in case another index is given this name before this async request is processed. It'd be better + // to have a real unique ID for each index. + if (rawIndex === rawIndex2) { + this._rawObjectStore.rawIndexes.delete(name); + } + }, + source: this + }); + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBObjectStore-count-IDBRequest-any-key + count(key) { + confirmActiveTransaction(this); + if (key === null) { + key = undefined; + } + if (key !== undefined && !(key instanceof _FDBKeyRange.default)) { + key = _FDBKeyRange.default.only((0, _valueToKey.default)(key)); + } + return this.transaction._execRequestAsync({ + operation: () => { + return this._rawObjectStore.count(key); + }, + source: this + }); + } + get [Symbol.toStringTag]() { + return "IDBObjectStore"; + } +} +var _default = exports.default = FDBObjectStore; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/FDBOpenDBRequest.js b/node_modules/fake-indexeddb/build/cjs/FDBOpenDBRequest.js new file mode 100644 index 0000000000000000000000000000000000000000..469235fde129cf52c99939f0ba4c9b712f59fb3c --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/FDBOpenDBRequest.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _FDBRequest = _interopRequireDefault(require("./FDBRequest.js")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +class FDBOpenDBRequest extends _FDBRequest.default { + onupgradeneeded = null; + onblocked = null; + get [Symbol.toStringTag]() { + return "IDBOpenDBRequest"; + } +} +var _default = exports.default = FDBOpenDBRequest; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/FDBRecord.js b/node_modules/fake-indexeddb/build/cjs/FDBRecord.js new file mode 100644 index 0000000000000000000000000000000000000000..6d426968dcdb03c12d3b3ed9472c80d889faeda9 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/FDBRecord.js @@ -0,0 +1,36 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +class FDBRecord { + constructor(key, primaryKey, value) { + this._key = key; + this._primaryKey = primaryKey; + this._value = value; + } + get key() { + return this._key; + } + set key(_) { + /* for babel */ + } + get primaryKey() { + return this._primaryKey; + } + set primaryKey(_) { + /* for babel */ + } + get value() { + return this._value; + } + set value(_) { + /* for babel */ + } + get [Symbol.toStringTag]() { + return "IDBRecord"; + } +} +var _default = exports.default = FDBRecord; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/FDBRequest.js b/node_modules/fake-indexeddb/build/cjs/FDBRequest.js new file mode 100644 index 0000000000000000000000000000000000000000..0737d9be1e2ba75e285437a49b56a20ab2561a89 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/FDBRequest.js @@ -0,0 +1,41 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _errors = require("./lib/errors.js"); +var _FakeEventTarget = _interopRequireDefault(require("./lib/FakeEventTarget.js")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +class FDBRequest extends _FakeEventTarget.default { + _result = null; + _error = null; + source = null; + transaction = null; + readyState = "pending"; + onsuccess = null; + onerror = null; + get error() { + if (this.readyState === "pending") { + throw new _errors.InvalidStateError(); + } + return this._error; + } + set error(value) { + this._error = value; + } + get result() { + if (this.readyState === "pending") { + throw new _errors.InvalidStateError(); + } + return this._result; + } + set result(value) { + this._result = value; + } + get [Symbol.toStringTag]() { + return "IDBRequest"; + } +} +var _default = exports.default = FDBRequest; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/FDBTransaction.js b/node_modules/fake-indexeddb/build/cjs/FDBTransaction.js new file mode 100644 index 0000000000000000000000000000000000000000..aea63bab6e8b88bcdb1aa3ff1fb5dbd24863aa67 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/FDBTransaction.js @@ -0,0 +1,272 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _FDBObjectStore = _interopRequireDefault(require("./FDBObjectStore.js")); +var _FDBRequest = _interopRequireDefault(require("./FDBRequest.js")); +var _errors = require("./lib/errors.js"); +var _FakeDOMStringList = _interopRequireDefault(require("./lib/FakeDOMStringList.js")); +var _FakeEvent = _interopRequireDefault(require("./lib/FakeEvent.js")); +var _FakeEventTarget = _interopRequireDefault(require("./lib/FakeEventTarget.js")); +var _scheduling = require("./lib/scheduling.js"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +const prioritizedListenerTypes = ["error", "abort", "complete"]; +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#transaction +class FDBTransaction extends _FakeEventTarget.default { + _state = "active"; + _started = false; + _rollbackLog = []; + _objectStoresCache = new Map(); + _openRequest = null; + error = null; + onabort = null; + oncomplete = null; + onerror = null; + _prioritizedListeners = new Map(); + _requests = []; + _createdIndexes = new Set(); + _createdObjectStores = new Set(); + constructor(storeNames, mode, durability, db) { + super(); + this._scope = new Set(storeNames); + this.mode = mode; + this.durability = durability; + this.db = db; + this.objectStoreNames = new _FakeDOMStringList.default(...Array.from(this._scope).sort()); + for (const type of prioritizedListenerTypes) { + // Attach prioritized (internal) listeners before any external listeners are attached. + // This ensures that these listeners run with the same timing regardless of whether + // the user uses `on*` or `addEventListener` for event listeners. + this.addEventListener(type, () => { + this._prioritizedListeners.get(type)?.(); + }); + } + } + + // https://w3c.github.io/IndexedDB/#abort-transaction + _abort(errName) { + for (const f of this._rollbackLog.reverse()) { + f(); + } + if (errName !== null) { + const e = new DOMException(undefined, errName); + this.error = e; + } + + // Should this directly remove from _requests? + for (const { + request + } of this._requests) { + if (request.readyState !== "done") { + request.readyState = "done"; // This will cancel execution of this request's operation + if (request.source) { + // https://w3c.github.io/IndexedDB/#ref-for-list-iterate%E2%91%A2 + // For each request of transaction’s request list, abort the steps to asynchronously + // execute a request for request, set request’s processed flag to true, and queue a + // database task to run these steps: + (0, _scheduling.queueTask)(() => { + // Set request’s result to undefined. + request.result = undefined; + // Set request’s error to a newly created "AbortError" DOMException. + request.error = new _errors.AbortError(); + + // Fire an event named error at request with its bubbles and cancelable attributes initialized + // to true. + const event = new _FakeEvent.default("error", { + bubbles: true, + cancelable: true + }); + event.eventPath = [this.db, this]; + try { + request.dispatchEvent(event); + } catch (_err) { + if (this._state === "active") { + this._abort("AbortError"); + } + } + }); + } + } + } + + // Queue a database task to run these steps: + (0, _scheduling.queueTask)(() => { + // If transaction is an upgrade transaction, then set transaction’s connection’s associated database’s + // upgrade transaction to null. + // (i.e. remove it from the list of `db.connections`) + const isUpgradeTransaction = this.mode === "versionchange"; + if (isUpgradeTransaction) { + this.db._rawDatabase.connections = this.db._rawDatabase.connections.filter(connection => !connection._rawDatabase.transactions.includes(this)); + } + // Fire an event named abort at transaction with its bubbles attribute initialized to true. + const event = new _FakeEvent.default("abort", { + bubbles: true, + cancelable: false + }); + event.eventPath = [this.db]; + this.dispatchEvent(event); + + // If transaction is an upgrade transaction, then: + if (isUpgradeTransaction) { + // Let request be the open request associated with transaction. + const request = this._openRequest; + // Set request’s transaction to null. + request.transaction = null; + // Set request’s result to undefined. + request.result = undefined; + } + }); + this._state = "finished"; + } + abort() { + if (this._state === "committing" || this._state === "finished") { + throw new _errors.InvalidStateError(); + } + this._state = "active"; + this._abort(null); + } + + // http://w3c.github.io/IndexedDB/#dom-idbtransaction-objectstore + objectStore(name) { + if (this._state !== "active") { + throw new _errors.InvalidStateError(); + } + const objectStore = this._objectStoresCache.get(name); + if (objectStore !== undefined) { + return objectStore; + } + const rawObjectStore = this.db._rawDatabase.rawObjectStores.get(name); + if (!this._scope.has(name) || rawObjectStore === undefined) { + throw new _errors.NotFoundError(); + } + const objectStore2 = new _FDBObjectStore.default(this, rawObjectStore); + this._objectStoresCache.set(name, objectStore2); + return objectStore2; + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-asynchronously-executing-a-request + _execRequestAsync(obj) { + const source = obj.source; + const operation = obj.operation; + let request = Object.hasOwn(obj, "request") ? obj.request : null; + if (this._state !== "active") { + throw new _errors.TransactionInactiveError(); + } + + // Request should only be passed for cursors + if (!request) { + if (!source) { + // Special requests like indexes that just need to run some code + request = new _FDBRequest.default(); + } else { + request = new _FDBRequest.default(); + request.source = source; + request.transaction = source.transaction; + } + } + this._requests.push({ + operation, + request + }); + return request; + } + _start() { + this._started = true; + + // Remove from request queue - cursor ones will be added back if necessary by cursor.continue and such + let operation; + let request; + while (this._requests.length > 0) { + const r = this._requests.shift(); + + // This should only be false if transaction was aborted + if (r && r.request.readyState !== "done") { + request = r.request; + operation = r.operation; + break; + } + } + if (request && operation) { + if (!request.source) { + // Special requests like indexes that just need to run some code, with error handling already built into + // operation + operation(); + } else { + let defaultAction; + let event; + try { + const result = operation(); + request.readyState = "done"; + request.result = result; + request.error = undefined; + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-fire-a-success-event + if (this._state === "inactive") { + this._state = "active"; + } + event = new _FakeEvent.default("success", { + bubbles: false, + cancelable: false + }); + } catch (err) { + request.readyState = "done"; + request.result = undefined; + request.error = err; + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-fire-an-error-event + if (this._state === "inactive") { + this._state = "active"; + } + event = new _FakeEvent.default("error", { + bubbles: true, + cancelable: true + }); + defaultAction = this._abort.bind(this, err.name); + } + try { + event.eventPath = [this.db, this]; + request.dispatchEvent(event); + } catch (_err) { + if (this._state === "active") { + this._abort("AbortError"); + defaultAction = undefined; // do not abort again + } + } + + // Default action of event + if (!event.canceled) { + if (defaultAction) { + defaultAction(); + } + } + } + + // Give it another chance for new handlers to be set before finishing + (0, _scheduling.queueTask)(this._start.bind(this)); + return; + } + + // Check if transaction complete event needs to be fired + if (this._state !== "finished") { + // Either aborted or committed already + this._state = "finished"; + if (!this.error) { + const event = new _FakeEvent.default("complete"); + this.dispatchEvent(event); + } + } + } + commit() { + if (this._state !== "active") { + throw new _errors.InvalidStateError(); + } + this._state = "committing"; + } + get [Symbol.toStringTag]() { + return "IDBTransaction"; + } +} +var _default = exports.default = FDBTransaction; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/FDBVersionChangeEvent.js b/node_modules/fake-indexeddb/build/cjs/FDBVersionChangeEvent.js new file mode 100644 index 0000000000000000000000000000000000000000..e5ce83e33dc0eda4f914399401ff2a240485b7d5 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/FDBVersionChangeEvent.js @@ -0,0 +1,20 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _FakeEvent = _interopRequireDefault(require("./lib/FakeEvent.js")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +class FDBVersionChangeEvent extends _FakeEvent.default { + constructor(type, parameters = {}) { + super(type); + this.newVersion = parameters.newVersion !== undefined ? parameters.newVersion : null; + this.oldVersion = parameters.oldVersion !== undefined ? parameters.oldVersion : 0; + } + get [Symbol.toStringTag]() { + return "IDBVersionChangeEvent"; + } +} +var _default = exports.default = FDBVersionChangeEvent; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/fakeIndexedDB.js b/node_modules/fake-indexeddb/build/cjs/fakeIndexedDB.js new file mode 100644 index 0000000000000000000000000000000000000000..8d7ecc0479eee16aa6da754a77f841e8d769f71a --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/fakeIndexedDB.js @@ -0,0 +1,11 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _FDBFactory = _interopRequireDefault(require("./FDBFactory.js")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +const fakeIndexedDB = new _FDBFactory.default(); +var _default = exports.default = fakeIndexedDB; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/forceCloseDatabase.js b/node_modules/fake-indexeddb/build/cjs/forceCloseDatabase.js new file mode 100644 index 0000000000000000000000000000000000000000..c6f259ea60002297a90797029f2d76d6addfaea6 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/forceCloseDatabase.js @@ -0,0 +1,29 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = forceCloseDatabase; +var _closeConnection = _interopRequireDefault(require("./lib/closeConnection.js")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +/** + * Forcibly closes a database. This simulates a database being closed due to abnormal reasons, such as + * using DevTools to clear data while a database is open. Spec-wise, this is equivalent to + * [closing a database connection](https://www.w3.org/TR/IndexedDB/#closing-connection) with the `forced flag` + * set to true. + * + * Use this API if you want to have more test coverage for unusual IndexedDB events, such as a database firing + * the "close" event: + * + * ```js + * db.addEventListener("close", () => { + * console.log("Forcibly closed!"); + * }); + * forceCloseDatabase(db); // invokes the event listener + * ``` + * @param db + */ +function forceCloseDatabase(db) { + (0, _closeConnection.default)(db, true); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/index.js b/node_modules/fake-indexeddb/build/cjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..07e7643a2b375c12709ccd505172199503fc8e64 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/index.js @@ -0,0 +1,106 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "IDBCursor", { + enumerable: true, + get: function () { + return _FDBCursor.default; + } +}); +Object.defineProperty(exports, "IDBCursorWithValue", { + enumerable: true, + get: function () { + return _FDBCursorWithValue.default; + } +}); +Object.defineProperty(exports, "IDBDatabase", { + enumerable: true, + get: function () { + return _FDBDatabase.default; + } +}); +Object.defineProperty(exports, "IDBFactory", { + enumerable: true, + get: function () { + return _FDBFactory.default; + } +}); +Object.defineProperty(exports, "IDBIndex", { + enumerable: true, + get: function () { + return _FDBIndex.default; + } +}); +Object.defineProperty(exports, "IDBKeyRange", { + enumerable: true, + get: function () { + return _FDBKeyRange.default; + } +}); +Object.defineProperty(exports, "IDBObjectStore", { + enumerable: true, + get: function () { + return _FDBObjectStore.default; + } +}); +Object.defineProperty(exports, "IDBOpenDBRequest", { + enumerable: true, + get: function () { + return _FDBOpenDBRequest.default; + } +}); +Object.defineProperty(exports, "IDBRecord", { + enumerable: true, + get: function () { + return _FDBRecord.default; + } +}); +Object.defineProperty(exports, "IDBRequest", { + enumerable: true, + get: function () { + return _FDBRequest.default; + } +}); +Object.defineProperty(exports, "IDBTransaction", { + enumerable: true, + get: function () { + return _FDBTransaction.default; + } +}); +Object.defineProperty(exports, "IDBVersionChangeEvent", { + enumerable: true, + get: function () { + return _FDBVersionChangeEvent.default; + } +}); +exports.default = void 0; +Object.defineProperty(exports, "forceCloseDatabase", { + enumerable: true, + get: function () { + return _forceCloseDatabase.default; + } +}); +Object.defineProperty(exports, "indexedDB", { + enumerable: true, + get: function () { + return _fakeIndexedDB.default; + } +}); +var _fakeIndexedDB = _interopRequireDefault(require("./fakeIndexedDB.js")); +var _FDBCursor = _interopRequireDefault(require("./FDBCursor.js")); +var _FDBCursorWithValue = _interopRequireDefault(require("./FDBCursorWithValue.js")); +var _FDBDatabase = _interopRequireDefault(require("./FDBDatabase.js")); +var _FDBFactory = _interopRequireDefault(require("./FDBFactory.js")); +var _FDBIndex = _interopRequireDefault(require("./FDBIndex.js")); +var _FDBKeyRange = _interopRequireDefault(require("./FDBKeyRange.js")); +var _FDBObjectStore = _interopRequireDefault(require("./FDBObjectStore.js")); +var _FDBOpenDBRequest = _interopRequireDefault(require("./FDBOpenDBRequest.js")); +var _FDBRecord = _interopRequireDefault(require("./FDBRecord.js")); +var _FDBRequest = _interopRequireDefault(require("./FDBRequest.js")); +var _FDBTransaction = _interopRequireDefault(require("./FDBTransaction.js")); +var _FDBVersionChangeEvent = _interopRequireDefault(require("./FDBVersionChangeEvent.js")); +var _forceCloseDatabase = _interopRequireDefault(require("./forceCloseDatabase.js")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +var _default = exports.default = _fakeIndexedDB.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/Database.js b/node_modules/fake-indexeddb/build/cjs/lib/Database.js new file mode 100644 index 0000000000000000000000000000000000000000..55f95ce0d2d8e6a668f2a86929bfa97974785f35 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/Database.js @@ -0,0 +1,51 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _scheduling = require("./scheduling.js"); +var _intersection = require("./intersection.js"); +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-database +class Database { + transactions = []; + rawObjectStores = new Map(); + connections = []; + constructor(name, version) { + this.name = name; + this.version = version; + this.processTransactions = this.processTransactions.bind(this); + } + processTransactions() { + (0, _scheduling.queueTask)(() => { + const running = this.transactions.filter(transaction => transaction._started && transaction._state !== "finished"); + const waiting = this.transactions.filter(transaction => !transaction._started && transaction._state !== "finished"); + + // The next transaction to run is the first waiting one that doesn't overlap with either a running one or a + // preceding waiting one. This allows non-overlapping transactions to run in parallel. + // The exception is readonly transactions, which are allowed to run in parallel with other readonly + // transactions, even with overlapping scopes, since no data is being modified. + const next = waiting.find((transaction, i) => { + const anyRunning = running.some(other => !(transaction.mode === "readonly" && other.mode === "readonly") && (0, _intersection.intersection)(other._scope, transaction._scope).size > 0); + if (anyRunning) { + return false; + } + + // If any _preceding_ waiting transactions are blocked, then that's also blocking. + // E.g. if you have 3 transactions: [a], [a,b], and [b,c], then [a] blocks [a,b] which blocks [b,c] + // until [a] is complete, even though [a] and [b,c] share no overlap. + // Note that readonly transactions do not have to be handled as a special case here, + // because if any transactions with overlapping scopes are blocked, then we can assume they are + const anyWaiting = waiting.slice(0, i).some(other => (0, _intersection.intersection)(other._scope, transaction._scope).size > 0); + return !anyWaiting; + }); + if (next) { + next.addEventListener("complete", this.processTransactions); + next.addEventListener("abort", this.processTransactions); + next._start(); + } + }); + } +} +var _default = exports.default = Database; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/FakeDOMStringList.js b/node_modules/fake-indexeddb/build/cjs/lib/FakeDOMStringList.js new file mode 100644 index 0000000000000000000000000000000000000000..899229445d94383affc3302f009affd2dbe7b9de --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/FakeDOMStringList.js @@ -0,0 +1,48 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +class FakeDOMStringList { + constructor(...values) { + this._values = values; + for (let i = 0; i < values.length; i++) { + this[i] = values[i]; + } + } + contains(value) { + return this._values.includes(value); + } + item(i) { + if (i < 0 || i >= this._values.length) { + return null; + } + return this._values[i]; + } + get length() { + return this._values.length; + } + [Symbol.iterator]() { + return this._values[Symbol.iterator](); + } + + // Handled by proxy + + // Used internally, should not be used by others. I could maybe get rid of these and replace rather than mutate, but too lazy to check the spec. + _push(...values) { + for (let i = 0; i < values.length; i++) { + this[this._values.length + i] = values[i]; + } + this._values.push(...values); + } + _sort(...values) { + this._values.sort(...values); + for (let i = 0; i < this._values.length; i++) { + this[i] = this._values[i]; + } + return this; + } +} +var _default = exports.default = FakeDOMStringList; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/FakeEvent.js b/node_modules/fake-indexeddb/build/cjs/lib/FakeEvent.js new file mode 100644 index 0000000000000000000000000000000000000000..a8945e1aa212a2b90c5a3037aeac52c132e7e499 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/FakeEvent.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +class Event { + eventPath = []; + NONE = 0; + CAPTURING_PHASE = 1; + AT_TARGET = 2; + BUBBLING_PHASE = 3; + + // Flags + propagationStopped = false; + immediatePropagationStopped = false; + canceled = false; + initialized = true; + dispatched = false; + target = null; + currentTarget = null; + eventPhase = 0; + defaultPrevented = false; + isTrusted = false; + timeStamp = Date.now(); + constructor(type, eventInitDict = {}) { + this.type = type; + this.bubbles = eventInitDict.bubbles !== undefined ? eventInitDict.bubbles : false; + this.cancelable = eventInitDict.cancelable !== undefined ? eventInitDict.cancelable : false; + } + preventDefault() { + if (this.cancelable) { + this.canceled = true; + } + } + stopPropagation() { + this.propagationStopped = true; + } + stopImmediatePropagation() { + this.propagationStopped = true; + this.immediatePropagationStopped = true; + } +} +var _default = exports.default = Event; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/FakeEventTarget.js b/node_modules/fake-indexeddb/build/cjs/lib/FakeEventTarget.js new file mode 100644 index 0000000000000000000000000000000000000000..3b7ba0b0ea20530680c3c0e08ea07c83f2ad2bf1 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/FakeEventTarget.js @@ -0,0 +1,127 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _errors = require("./errors.js"); +const stopped = (event, listener) => { + return event.immediatePropagationStopped || event.eventPhase === event.CAPTURING_PHASE && listener.capture === false || event.eventPhase === event.BUBBLING_PHASE && listener.capture === true; +}; + +// http://www.w3.org/TR/dom/#concept-event-listener-invoke +const invokeEventListeners = (event, obj) => { + event.currentTarget = obj; + const errors = []; + const invoke = callbackOrObject => { + try { + const callback = typeof callbackOrObject === "function" ? callbackOrObject : callbackOrObject.handleEvent; + // @ts-expect-error EventCallback's types are not quite right here + callback.call(event.currentTarget, event); + } catch (err) { + errors.push(err); + } + }; + + // The callback might cause obj.listeners to mutate as we traverse it. + // Take a copy of the array so that nothing sneaks in and we don't lose + // our place. + for (const listener of obj.listeners.slice()) { + if (event.type !== listener.type || stopped(event, listener)) { + continue; + } + invoke(listener.callback); + } + const typeToProp = { + abort: "onabort", + blocked: "onblocked", + close: "onclose", + complete: "oncomplete", + error: "onerror", + success: "onsuccess", + upgradeneeded: "onupgradeneeded", + versionchange: "onversionchange" + }; + const prop = typeToProp[event.type]; + if (prop === undefined) { + throw new Error(`Unknown event type: "${event.type}"`); + } + const callback = event.currentTarget[prop]; + if (callback) { + const listener = { + callback, + capture: false, + type: event.type + }; + if (!stopped(event, listener)) { + invoke(listener.callback); + } + } + + // we want to execute all listeners before deciding if we want to throw, because there could be an error thrown by + // the first listener, but the second should still be invoked + if (errors.length) { + throw new AggregateError(errors); + } +}; +class FakeEventTarget { + listeners = []; + + // These will be overridden in individual subclasses and made not readonly + + addEventListener(type, callback, options) { + const capture = !!(typeof options === "object" && options ? options.capture : options); + this.listeners.push({ + callback, + capture, + type + }); + } + removeEventListener(type, callback, options) { + const capture = !!(typeof options === "object" && options ? options.capture : options); + const i = this.listeners.findIndex(listener => { + return listener.type === type && listener.callback === callback && listener.capture === capture; + }); + this.listeners.splice(i, 1); + } + + // http://www.w3.org/TR/dom/#dispatching-events + dispatchEvent(event) { + if (event.dispatched || !event.initialized) { + throw new _errors.InvalidStateError("The object is in an invalid state."); + } + event.isTrusted = false; + event.dispatched = true; + event.target = this; + // NOT SURE WHEN THIS SHOULD BE SET event.eventPath = []; + + event.eventPhase = event.CAPTURING_PHASE; + for (const obj of event.eventPath) { + if (!event.propagationStopped) { + invokeEventListeners(event, obj); + } + } + event.eventPhase = event.AT_TARGET; + if (!event.propagationStopped) { + invokeEventListeners(event, event.target); + } + if (event.bubbles) { + event.eventPath.reverse(); + event.eventPhase = event.BUBBLING_PHASE; + for (const obj of event.eventPath) { + if (!event.propagationStopped) { + invokeEventListeners(event, obj); + } + } + } + event.dispatched = false; + event.eventPhase = event.NONE; + event.currentTarget = null; + if (event.canceled) { + return false; + } + return true; + } +} +var _default = exports.default = FakeEventTarget; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/Index.js b/node_modules/fake-indexeddb/build/cjs/lib/Index.js new file mode 100644 index 0000000000000000000000000000000000000000..ee17791247174a3cfe8ec6f5054b496b36602f57 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/Index.js @@ -0,0 +1,180 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _FDBRecord = _interopRequireDefault(require("../FDBRecord.js")); +var _errors = require("./errors.js"); +var _extractKey = _interopRequireDefault(require("./extractKey.js")); +var _RecordStore = _interopRequireDefault(require("./RecordStore.js")); +var _valueToKey = _interopRequireDefault(require("./valueToKey.js")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-index +class Index { + deleted = false; + // Initialized should be used to decide whether to throw an error or abort the versionchange transaction when there is a + // constraint + initialized = false; + constructor(rawObjectStore, name, keyPath, multiEntry, unique) { + this.rawObjectStore = rawObjectStore; + this.name = name; + this.keyPath = keyPath; + this.multiEntry = multiEntry; + this.unique = unique; + this.records = new _RecordStore.default(unique); + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-retrieving-a-value-from-an-index + getKey(key) { + const record = this.records.get(key); + return record !== undefined ? record.value : undefined; + } + + // http://w3c.github.io/IndexedDB/#retrieve-multiple-referenced-values-from-an-index + getAllKeys(range, count, direction) { + if (count === undefined || count === 0) { + count = Infinity; + } + const records = []; + for (const record of this.records.values(range, direction)) { + records.push(structuredClone(record.value)); + if (records.length >= count) { + break; + } + } + return records; + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#index-referenced-value-retrieval-operation + getValue(key) { + const record = this.records.get(key); + return record !== undefined ? this.rawObjectStore.getValue(record.value) : undefined; + } + + // http://w3c.github.io/IndexedDB/#retrieve-multiple-referenced-values-from-an-index + getAllValues(range, count, direction) { + if (count === undefined || count === 0) { + count = Infinity; + } + const records = []; + for (const record of this.records.values(range, direction)) { + records.push(this.rawObjectStore.getValue(record.value)); + if (records.length >= count) { + break; + } + } + return records; + } + + // https://www.w3.org/TR/IndexedDB/#dom-idbindex-getallrecords + getAllRecords(range, count, direction) { + if (count === undefined || count === 0) { + count = Infinity; + } + const records = []; + for (const record of this.records.values(range, direction)) { + records.push(new _FDBRecord.default(structuredClone(record.key), structuredClone(this.rawObjectStore.getKey(record.value)), this.rawObjectStore.getValue(record.value))); + if (records.length >= count) { + break; + } + } + return records; + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-storing-a-record-into-an-object-store (step 7) + storeRecord(newRecord) { + let indexKey; + try { + indexKey = (0, _extractKey.default)(this.keyPath, newRecord.value).key; + } catch (err) { + if (err.name === "DataError") { + // Invalid key is not an actual error, just means we do not store an entry in this index + return; + } + throw err; + } + if (!this.multiEntry || !Array.isArray(indexKey)) { + try { + (0, _valueToKey.default)(indexKey); + } catch (e) { + return; + } + } else { + // remove any elements from index key that are not valid keys and remove any duplicate elements from index + // key such that only one instance of the duplicate value remains. + const keep = []; + for (const part of indexKey) { + if (keep.indexOf(part) < 0) { + try { + keep.push((0, _valueToKey.default)(part)); + } catch (err) { + /* Do nothing */ + } + } + } + indexKey = keep; + } + if (!this.multiEntry || !Array.isArray(indexKey)) { + if (this.unique) { + const existingRecord = this.records.get(indexKey); + if (existingRecord) { + throw new _errors.ConstraintError(); + } + } + } else { + if (this.unique) { + for (const individualIndexKey of indexKey) { + const existingRecord = this.records.get(individualIndexKey); + if (existingRecord) { + throw new _errors.ConstraintError(); + } + } + } + } + if (!this.multiEntry || !Array.isArray(indexKey)) { + this.records.put({ + key: indexKey, + value: newRecord.key + }); + } else { + for (const individualIndexKey of indexKey) { + this.records.put({ + key: individualIndexKey, + value: newRecord.key + }); + } + } + } + initialize(transaction) { + if (this.initialized) { + throw new Error("Index already initialized"); + } + transaction._execRequestAsync({ + operation: () => { + try { + // Create index based on current value of objectstore + for (const record of this.rawObjectStore.records.values()) { + this.storeRecord(record); + } + this.initialized = true; + } catch (err) { + // console.error(err); + transaction._abort(err.name); + } + }, + source: null + }); + } + count(range) { + let count = 0; + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + for (const record of this.records.values(range)) { + count += 1; + } + return count; + } +} +var _default = exports.default = Index; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/KeyGenerator.js b/node_modules/fake-indexeddb/build/cjs/lib/KeyGenerator.js new file mode 100644 index 0000000000000000000000000000000000000000..4edd863f88106e938e7055d7ddcf3f7b4fd11b09 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/KeyGenerator.js @@ -0,0 +1,29 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _errors = require("./errors.js"); +const MAX_KEY = 9007199254740992; +class KeyGenerator { + // This is kind of wrong. Should start at 1 and increment only after record is saved + num = 0; + next() { + if (this.num >= MAX_KEY) { + throw new _errors.ConstraintError(); + } + this.num += 1; + return this.num; + } + + // https://w3c.github.io/IndexedDB/#possibly-update-the-key-generator + setIfLarger(num) { + const value = Math.floor(Math.min(num, MAX_KEY)) - 1; + if (value >= this.num) { + this.num = value + 1; + } + } +} +var _default = exports.default = KeyGenerator; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/ObjectStore.js b/node_modules/fake-indexeddb/build/cjs/lib/ObjectStore.js new file mode 100644 index 0000000000000000000000000000000000000000..b9be024817bd4150e35a5f462a98284aa6c4a0bf --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/ObjectStore.js @@ -0,0 +1,246 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _FDBRecord = _interopRequireDefault(require("../FDBRecord.js")); +var _errors = require("./errors.js"); +var _extractKey = _interopRequireDefault(require("./extractKey.js")); +var _KeyGenerator = _interopRequireDefault(require("./KeyGenerator.js")); +var _RecordStore = _interopRequireDefault(require("./RecordStore.js")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-object-store +class ObjectStore { + deleted = false; + records = new _RecordStore.default(true); + rawIndexes = new Map(); + constructor(rawDatabase, name, keyPath, autoIncrement) { + this.rawDatabase = rawDatabase; + this.keyGenerator = autoIncrement === true ? new _KeyGenerator.default() : null; + this.deleted = false; + this.name = name; + this.keyPath = keyPath; + this.autoIncrement = autoIncrement; + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-retrieving-a-value-from-an-object-store + getKey(key) { + const record = this.records.get(key); + return record !== undefined ? structuredClone(record.key) : undefined; + } + + // http://w3c.github.io/IndexedDB/#retrieve-multiple-keys-from-an-object-store + getAllKeys(range, count, direction) { + if (count === undefined || count === 0) { + count = Infinity; + } + const records = []; + for (const record of this.records.values(range, direction)) { + records.push(structuredClone(record.key)); + if (records.length >= count) { + break; + } + } + return records; + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-retrieving-a-value-from-an-object-store + getValue(key) { + const record = this.records.get(key); + return record !== undefined ? structuredClone(record.value) : undefined; + } + + // http://w3c.github.io/IndexedDB/#retrieve-multiple-values-from-an-object-store + getAllValues(range, count, direction) { + if (count === undefined || count === 0) { + count = Infinity; + } + const records = []; + for (const record of this.records.values(range, direction)) { + records.push(structuredClone(record.value)); + if (records.length >= count) { + break; + } + } + return records; + } + + // https://www.w3.org/TR/IndexedDB/#dom-idbobjectstore-getallrecords + getAllRecords(range, count, direction) { + if (count === undefined || count === 0) { + count = Infinity; + } + const records = []; + for (const record of this.records.values(range, direction)) { + records.push(new _FDBRecord.default(structuredClone(record.key), structuredClone(record.key), structuredClone(record.value))); + if (records.length >= count) { + break; + } + } + return records; + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-storing-a-record-into-an-object-store + storeRecord(newRecord, noOverwrite, rollbackLog) { + if (this.keyPath !== null) { + const key = (0, _extractKey.default)(this.keyPath, newRecord.value).key; + if (key !== undefined) { + newRecord.key = key; + } + } + const rollbackLogForThisOperation = []; + if (this.keyGenerator !== null && newRecord.key === undefined) { + let rolledBack = false; + const keyGeneratorBefore = this.keyGenerator.num; + const rollbackKeyGenerator = () => { + if (rolledBack) { + return; + } + rolledBack = true; + if (this.keyGenerator) { + this.keyGenerator.num = keyGeneratorBefore; + } + }; + rollbackLogForThisOperation.push(rollbackKeyGenerator); + if (rollbackLog) { + rollbackLog.push(rollbackKeyGenerator); + } + newRecord.key = this.keyGenerator.next(); + + // Set in value if keyPath defiend but led to no key + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-to-assign-a-key-to-a-value-using-a-key-path + if (this.keyPath !== null) { + if (Array.isArray(this.keyPath)) { + throw new Error("Cannot have an array key path in an object store with a key generator"); + } + let remainingKeyPath = this.keyPath; + let object = newRecord.value; + let identifier; + let i = 0; // Just to run the loop at least once + while (i >= 0) { + if (typeof object !== "object") { + throw new _errors.DataError(); + } + i = remainingKeyPath.indexOf("."); + if (i >= 0) { + identifier = remainingKeyPath.slice(0, i); + remainingKeyPath = remainingKeyPath.slice(i + 1); + if (!Object.hasOwn(object, identifier)) { + // Bypass prototype when setting (See `bindings-inject-values-bypass.any.js`) + // Equivalent to `object[identifier] = ...` without using `Object.prototype` + Object.defineProperty(object, identifier, { + configurable: true, + enumerable: true, + writable: true, + value: {} + }); + } + object = object[identifier]; + } + } + identifier = remainingKeyPath; + + // Bypass prototype when setting (See `bindings-inject-values-bypass.any.js`) + // Equivalent to `object[identifier] = ...` without using `Object.prototype` + Object.defineProperty(object, identifier, { + configurable: true, + enumerable: true, + writable: true, + value: newRecord.key + }); + } + } else if (this.keyGenerator !== null && typeof newRecord.key === "number") { + this.keyGenerator.setIfLarger(newRecord.key); + } + const existingRecord = this.records.put(newRecord, noOverwrite); + let rolledBack = false; + const rollbackStoreRecord = () => { + if (rolledBack) { + return; + } + rolledBack = true; + if (existingRecord) { + // overwrite on rollback + this.storeRecord(existingRecord, false); + } else { + // delete on rollback + this.deleteRecord(newRecord.key); + } + }; + rollbackLogForThisOperation.push(rollbackStoreRecord); + if (rollbackLog) { + rollbackLog.push(rollbackStoreRecord); + } + + // Delete existing indexes + if (existingRecord) { + for (const rawIndex of this.rawIndexes.values()) { + rawIndex.records.deleteByValue(newRecord.key); + } + } + + // Update indexes + try { + for (const rawIndex of this.rawIndexes.values()) { + if (rawIndex.initialized) { + rawIndex.storeRecord(newRecord); + } + } + } catch (err) { + // If this request fails here and preventDefault is used to stop the transaction from aborting, we need to roll back the addition of this record to the store, otherwise it will be present in subsequent requests on this transaction. Same for key generator. + if (err.name === "ConstraintError") { + for (const rollback of rollbackLogForThisOperation) { + rollback(); + } + } + throw err; + } + return newRecord.key; + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-deleting-records-from-an-object-store + deleteRecord(key, rollbackLog) { + const deletedRecords = this.records.delete(key); + if (rollbackLog) { + for (const record of deletedRecords) { + rollbackLog.push(() => { + this.storeRecord(record, true); + }); + } + } + for (const rawIndex of this.rawIndexes.values()) { + rawIndex.records.deleteByValue(key); + } + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-clearing-an-object-store + clear(rollbackLog) { + const deletedRecords = this.records.clear(); + if (rollbackLog) { + for (const record of deletedRecords) { + rollbackLog.push(() => { + this.storeRecord(record, true); + }); + } + } + for (const rawIndex of this.rawIndexes.values()) { + rawIndex.records.clear(); + } + } + count(range) { + // optimization: if there is no range, or if the range is everything, then we can just count the total size + if (range === undefined || range.lower === undefined && range.upper === undefined) { + return this.records.size(); + } + let count = 0; + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + for (const record of this.records.values(range)) { + count += 1; + } + return count; + } +} +var _default = exports.default = ObjectStore; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/RecordStore.js b/node_modules/fake-indexeddb/build/cjs/lib/RecordStore.js new file mode 100644 index 0000000000000000000000000000000000000000..6de35896debcc16f3ca24a42a87dbc0a644e6895 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/RecordStore.js @@ -0,0 +1,112 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _FDBKeyRange = _interopRequireDefault(require("../FDBKeyRange.js")); +var _cmp = _interopRequireDefault(require("./cmp.js")); +var _binarySearchTree = _interopRequireDefault(require("./binarySearchTree.js")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +class RecordStore { + constructor(keysAreUnique) { + this.keysAreUnique = keysAreUnique; + this.records = new _binarySearchTree.default(this.keysAreUnique); + } + get(key) { + const range = key instanceof _FDBKeyRange.default ? key : _FDBKeyRange.default.only(key); + return this.records.getRecords(range).next().value; + } + + /** + * Put a new record, and return the overwritten record if an overwrite occurred. + * @param newRecord + * @param noOverwrite - throw a ConstraintError in case of overwrite + */ + put(newRecord, noOverwrite = false) { + return this.records.put(newRecord, noOverwrite); + } + delete(key) { + const range = key instanceof _FDBKeyRange.default ? key : _FDBKeyRange.default.only(key); + const deletedRecords = [...this.records.getRecords(range)]; + for (const record of deletedRecords) { + this.records.delete(record); + } + return deletedRecords; + } + deleteByValue(key) { + const range = key instanceof _FDBKeyRange.default ? key : _FDBKeyRange.default.only(key); + const deletedRecords = []; + for (const record of this.records.getAllRecords()) { + if (range.includes(record.value)) { + this.records.delete(record); + deletedRecords.push(record); + } + } + return deletedRecords; + } + clear() { + const deletedRecords = [...this.records.getAllRecords()]; + this.records = new _binarySearchTree.default(this.keysAreUnique); + return deletedRecords; + } + values(range, direction = "next") { + const descending = direction === "prev" || direction === "prevunique"; + const records = range ? this.records.getRecords(range, descending) : this.records.getAllRecords(descending); + return { + [Symbol.iterator]: () => { + const next = () => { + return records.next(); + }; + if (direction === "next" || direction === "prev") { + return { + next + }; + } + + // For nextunique/prevunique, return an iterator that skips seen values + // Note that we must return the _lowest_ value regardless of direction: + // > Iterating with "prevunique" visits the same records that "nextunique" + // > visits, but in reverse order. + // https://w3c.github.io/IndexedDB/#dom-idbcursordirection-prevunique + if (direction === "nextunique") { + let previousValue = undefined; + return { + next: () => { + let current = next(); + // for nextunique, continue if we already emitted the lowest unique value + while (!current.done && previousValue !== undefined && (0, _cmp.default)(previousValue.key, current.value.key) === 0) { + current = next(); + } + previousValue = current.value; + return current; + } + }; + } + + // prevunique is a bit more complex due to needing to check the next value, which + // invokes the iterable, so we need to keep a buffer of one "lookahead" result + let current = next(); + let nextResult = next(); + return { + next: () => { + while (!nextResult.done && (0, _cmp.default)(current.value.key, nextResult.value.key) === 0) { + // note we return the _lowest_ possible value, hence set the current + current = nextResult; + nextResult = next(); + } + const result = current; + current = nextResult; + nextResult = next(); + return result; + } + }; + } + }; + } + size() { + return this.records.size(); + } +} +var _default = exports.default = RecordStore; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/binarySearchTree.js b/node_modules/fake-indexeddb/build/cjs/lib/binarySearchTree.js new file mode 100644 index 0000000000000000000000000000000000000000..3b80a01c6c0a8ada0f6ab3aa65f044f8df7e0035 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/binarySearchTree.js @@ -0,0 +1,308 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _FDBKeyRange = _interopRequireDefault(require("../FDBKeyRange.js")); +var _cmp = _interopRequireDefault(require("./cmp.js")); +var _errors = require("./errors.js"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +// what fraction of the total number of nodes are allowed to be deleted tombstones? +const MAX_TOMBSTONE_FACTOR = 2 / 3; +const EVERYTHING_KEY_RANGE = new _FDBKeyRange.default(undefined, undefined, false, false); +/** + * Simple red-black binary tree with some aspects of a scapegoat tree. The main goal here is simplicity of + * implementation, tailored to the needs of IndexedDB. + * + * Basically this implements a [red-black tree][1] for insertions, but uses the much simpler [scapegoat tree][2] + * strategy for deletions. Deletions are a simple matter of rebuilding the tree from scratch if more than 2/3 of the + * tree is full of deleted (tombstone) markers. + * + * [1]: https://en.wikipedia.org/wiki/Red%E2%80%93black_tree + * [2]: https://en.wikipedia.org/wiki/Scapegoat_tree + */ +class BinarySearchTree { + _numTombstones = 0; + _numNodes = 0; + + /** + * + * @param keysAreUnique - whether keys can be unique, and thus whether we cn skip checking `record.value` when + * comparing. This is basically used to distinguish ObjectStores (where the value is the entire object, not used + * as a key) from non-unique Indexes (where both the key and the value are meaningful keys used for sorting) + */ + constructor(keysAreUnique) { + this._keysAreUnique = !!keysAreUnique; + } + size() { + return this._numNodes - this._numTombstones; + } + get(record) { + return this._getByComparator(this._root, otherRecord => this._compare(record, otherRecord)); + } + contains(record) { + return !!this.get(record); + } + _compare(a, b) { + const keyComparison = (0, _cmp.default)(a.key, b.key); + if (keyComparison !== 0) { + return keyComparison; + } + // if keys are unique, then we can (and must) avoid comparing the values, since they may be non-comparable + // (e.g. in the case of an ObjectStore, they are record objects) + return this._keysAreUnique ? 0 : (0, _cmp.default)(a.value, b.value); + } + _getByComparator(node, comparator) { + let current = node; + while (current) { + const comparison = comparator(current.record); + if (comparison < 0) { + current = current.left; + } else if (comparison > 0) { + current = current.right; + } else { + return current.record; + } + } + } + + /** + * Put a new record, and return the overwritten record if an overwrite occurred. + * @param record + * @param noOverwrite - throw a ConstraintError in case of overwrite + */ + put(record, noOverwrite = false) { + if (!this._root) { + this._root = { + record, + left: undefined, + right: undefined, + parent: undefined, + deleted: false, + // the root is always black in a red-black tree + red: false + }; + this._numNodes++; + return; + } + return this._put(this._root, record, noOverwrite); + } + _put(node, record, noOverwrite) { + const comparison = this._compare(record, node.record); + if (comparison < 0) { + if (node.left) { + return this._put(node.left, record, noOverwrite); + } else { + node.left = { + record, + left: undefined, + right: undefined, + parent: node, + deleted: false, + red: true + }; + this._onNewNodeInserted(node.left); + } + } else if (comparison > 0) { + if (node.right) { + return this._put(node.right, record, noOverwrite); + } else { + node.right = { + record, + left: undefined, + right: undefined, + parent: node, + deleted: false, + red: true + }; + this._onNewNodeInserted(node.right); + } + } else if (node.deleted) { + // undelete + node.deleted = false; + node.record = record; + this._numTombstones--; + } else if (noOverwrite) { + // replace not allowed in case of noOverwrite + throw new _errors.ConstraintError(); + } else { + // replace, don't add, so no need to increment. return the overwritten record + const overwrittenRecord = node.record; + node.record = record; + return overwrittenRecord; + } + } + delete(record) { + if (!this._root) { + return; + } + this._delete(this._root, record); + if (this._numTombstones > this._numNodes * MAX_TOMBSTONE_FACTOR) { + // to keep the implementation simple, and because most users of fake-indexeddb are not going to be deleting + // a lot of nodes, just rebuild the whole tree (defragment) if the tree is too full of tombstones, + // as inspired by the scapegoat tree: https://en.wikipedia.org/wiki/Scapegoat_tree#Deletion + const records = [...this.getAllRecords()]; + this._root = this._rebuild(records, undefined, false); + this._numNodes = records.length; + this._numTombstones = 0; + } + } + _delete(node, record) { + if (!node) { + return; + } + const comparison = this._compare(record, node.record); + if (comparison < 0) { + this._delete(node.left, record); + } else if (comparison > 0) { + this._delete(node.right, record); + } else if (!node.deleted) { + this._numTombstones++; + node.deleted = true; + } + } + *getAllRecords(descending = false) { + yield* this.getRecords(EVERYTHING_KEY_RANGE, descending); + } + *getRecords(keyRange, descending = false) { + yield* this._getRecordsForNode(this._root, keyRange, descending); + } + *_getRecordsForNode(node, keyRange, descending = false) { + if (!node) { + return; + } + yield* this._findRecords(node, keyRange, descending); + } + *_findRecords(node, keyRange, descending = false) { + const { + lower, + upper, + lowerOpen, + upperOpen + } = keyRange; + const { + record: { + key + } + } = node; + const lowerComparison = lower === undefined ? -1 : (0, _cmp.default)(lower, key); + const upperComparison = upper === undefined ? 1 : (0, _cmp.default)(upper, key); + + // if keys are non-unique then we need to go left/right even for equality + // else we can just do LT/GT rather than LTE/GTE as a slight optimization + const moreLeft = this._keysAreUnique ? lowerComparison < 0 : lowerComparison <= 0; + const moreRight = this._keysAreUnique ? upperComparison > 0 : upperComparison >= 0; + + // in descending mode we start with rightmost nodes, else leftmost + const moreStart = descending ? moreRight : moreLeft; + const moreEnd = descending ? moreLeft : moreRight; + const start = descending ? "right" : "left"; + const end = descending ? "left" : "right"; + + // does the current record actually match the key range? + const lowerMatches = lowerOpen ? lowerComparison < 0 : lowerComparison <= 0; + const upperMatches = upperOpen ? upperComparison > 0 : upperComparison >= 0; + if (moreStart && node[start]) { + yield* this._findRecords(node[start], keyRange, descending); + } + if (lowerMatches && upperMatches && !node.deleted) { + yield node.record; + } + if (moreEnd && node[end]) { + yield* this._findRecords(node[end], keyRange, descending); + } + } + _onNewNodeInserted(newNode) { + this._numNodes++; + this._rebalanceTree(newNode); + } + + // based on https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Insertion + _rebalanceTree(node) { + let parent = node.parent; + do { + // case 1 - no red/black violation + if (!parent.red) { + return; + } + const grandparent = parent.parent; + if (!grandparent) { + // case #4 - parent is the red root, node is also red, so parent goes black + parent.red = false; + return; + } + const parentIsRightChild = parent === grandparent.right; + const uncle = parentIsRightChild ? grandparent.left : grandparent.right; + if (!uncle || !uncle.red) { + if (node === (parentIsRightChild ? parent.left : parent.right)) { + // case #5 - parent is red but uncle is black + this._rotateSubtree(parent, parentIsRightChild); + node = parent; + parent = parentIsRightChild ? grandparent.right : grandparent.left; + } + + // case #6 - node is "outer" grandchild of grandparent + this._rotateSubtree(grandparent, !parentIsRightChild); + parent.red = false; + grandparent.red = true; + return; + } + + // case #2 - parent and uncle are both red, so both of them go black and grandparent goes red + parent.red = false; + uncle.red = false; + grandparent.red = true; + node = grandparent; + } while (node.parent ? parent = node.parent : false); + + // case #3 - current node is the root, all constraints satisfied + } + + // based on https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Implementation + _rotateSubtree(node, right) { + const parent = node.parent; + const newRoot = right ? node.left : node.right; // opposite direction + const newChild = right ? newRoot.right : newRoot.left; + node[right ? "left" : "right"] = newChild; + if (newChild) { + newChild.parent = node; + } + newRoot[right ? "right" : "left"] = node; + newRoot.parent = parent; + node.parent = newRoot; + if (parent) { + parent[node === parent.right ? "right" : "left"] = newRoot; + } else { + this._root = newRoot; + } + return newRoot; + } + + // rebuild the whole tree from scratch, used to avoid too many deletion tombstones accumulating + _rebuild(records, parent, red) { + const { + length + } = records; + if (!length) { + return undefined; + } + const mid = length >>> 1; // like Math.floor(records.length / 2) but fast + + const node = { + record: records[mid], + left: undefined, + right: undefined, + parent, + deleted: false, + red + }; + const left = this._rebuild(records.slice(0, mid), node, !red); + const right = this._rebuild(records.slice(mid + 1), node, !red); + node.left = left; + node.right = right; + return node; + } +} +exports.default = BinarySearchTree; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/canInjectKey.js b/node_modules/fake-indexeddb/build/cjs/lib/canInjectKey.js new file mode 100644 index 0000000000000000000000000000000000000000..023e5206eda3830f1368fe4fec50dac377672cab --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/canInjectKey.js @@ -0,0 +1,30 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +// http://w3c.github.io/IndexedDB/#check-that-a-key-could-be-injected-into-a-value +const canInjectKey = (keyPath, value) => { + if (Array.isArray(keyPath)) { + throw new Error("The key paths used in this section are always strings and never sequences, since it is not possible to create a object store which has a key generator and also has a key path that is a sequence."); + } + const identifiers = keyPath.split("."); + if (identifiers.length === 0) { + throw new Error("Assert: identifiers is not empty"); + } + identifiers.pop(); + for (const identifier of identifiers) { + if (typeof value !== "object" && !Array.isArray(value)) { + return false; + } + const hop = Object.hasOwn(value, identifier); + if (!hop) { + return true; + } + value = value[identifier]; + } + return typeof value === "object" || Array.isArray(value); +}; +var _default = exports.default = canInjectKey; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/cloneValueForInsertion.js b/node_modules/fake-indexeddb/build/cjs/lib/cloneValueForInsertion.js new file mode 100644 index 0000000000000000000000000000000000000000..39369ea8cd7c12ce9178fdfb6384282e472c110a --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/cloneValueForInsertion.js @@ -0,0 +1,30 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.cloneValueForInsertion = cloneValueForInsertion; +// https://w3c.github.io/IndexedDB/#clone-value +// Note that we only need to call this during insertions because the spec does not expect any cloning during retrieval, +// only `StructuredDeserialize()` (e.g. see [1]). This is also only required for values, not keys, since keys do not +// require cloning during insertion (e.g. see [2]). +// [1]: https://w3c.github.io/IndexedDB/#retrieve-multiple-items-from-an-object-store +// [2]: https://w3c.github.io/IndexedDB/#add-or-put +function cloneValueForInsertion(value, transaction) { + // Assert: transaction’s state is active. + if (transaction._state !== "active") { + throw new Error("Assert: transaction state is active"); + } + + // Set transaction’s state to inactive. + transaction._state = "inactive"; + try { + // Let serialized be StructuredSerializeForStorage(value). + // Let clone be ? StructuredDeserialize(serialized, targetRealm). + // Return clone. + return structuredClone(value); + } finally { + // Set transaction’s state to active. + transaction._state = "active"; + } +} \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/closeConnection.js b/node_modules/fake-indexeddb/build/cjs/lib/closeConnection.js new file mode 100644 index 0000000000000000000000000000000000000000..b99db54eaecdbc3ae6f1cffaba95fb16f2a32007 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/closeConnection.js @@ -0,0 +1,36 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _FakeEvent = _interopRequireDefault(require("./FakeEvent.js")); +var _scheduling = require("./scheduling.js"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#database-closing-steps +const closeConnection = (connection, forced = false) => { + connection._closePending = true; + const transactionsComplete = connection._rawDatabase.transactions.every(transaction => { + return transaction._state === "finished"; + }); + if (transactionsComplete) { + connection._closed = true; + connection._rawDatabase.connections = connection._rawDatabase.connections.filter(otherConnection => { + return connection !== otherConnection; + }); + if (forced) { + const event = new _FakeEvent.default("close", { + bubbles: false, + cancelable: false + }); + event.eventPath = []; + connection.dispatchEvent(event); + } + } else { + (0, _scheduling.queueTask)(() => { + closeConnection(connection, forced); + }); + } +}; +var _default = exports.default = closeConnection; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/cmp.js b/node_modules/fake-indexeddb/build/cjs/lib/cmp.js new file mode 100644 index 0000000000000000000000000000000000000000..8867dbffcd21973e2aef4bbeb826de6cf7630ca3 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/cmp.js @@ -0,0 +1,85 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _errors = require("./errors.js"); +var _valueToKey = _interopRequireDefault(require("./valueToKey.js")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +const getType = x => { + if (typeof x === "number") { + return "Number"; + } + if (Object.prototype.toString.call(x) === "[object Date]") { + return "Date"; + } + if (Array.isArray(x)) { + return "Array"; + } + if (typeof x === "string") { + return "String"; + } + if (x instanceof ArrayBuffer) { + return "Binary"; + } + throw new _errors.DataError(); +}; + +// https://w3c.github.io/IndexedDB/#compare-two-keys +const cmp = (first, second) => { + if (second === undefined) { + throw new TypeError(); + } + first = (0, _valueToKey.default)(first); + second = (0, _valueToKey.default)(second); + const t1 = getType(first); + const t2 = getType(second); + if (t1 !== t2) { + if (t1 === "Array") { + return 1; + } + if (t1 === "Binary" && (t2 === "String" || t2 === "Date" || t2 === "Number")) { + return 1; + } + if (t1 === "String" && (t2 === "Date" || t2 === "Number")) { + return 1; + } + if (t1 === "Date" && t2 === "Number") { + return 1; + } + return -1; + } + if (t1 === "Binary") { + first = new Uint8Array(first); + second = new Uint8Array(second); + } + if (t1 === "Array" || t1 === "Binary") { + const length = Math.min(first.length, second.length); + for (let i = 0; i < length; i++) { + const result = cmp(first[i], second[i]); + if (result !== 0) { + return result; + } + } + if (first.length > second.length) { + return 1; + } + if (first.length < second.length) { + return -1; + } + return 0; + } + if (t1 === "Date") { + if (first.getTime() === second.getTime()) { + return 0; + } + } else { + if (first === second) { + return 0; + } + } + return first > second ? 1 : -1; +}; +var _default = exports.default = cmp; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/enforceRange.js b/node_modules/fake-indexeddb/build/cjs/lib/enforceRange.js new file mode 100644 index 0000000000000000000000000000000000000000..b6bf95ad6dd55e61fc700c2998c81a5bcf5ff0ba --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/enforceRange.js @@ -0,0 +1,20 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +// https://heycam.github.io/webidl/#EnforceRange + +const enforceRange = (num, type) => { + const min = 0; + const max = type === "unsigned long" ? 4294967295 : 9007199254740991; + if (isNaN(num) || num < min || num > max) { + throw new TypeError(); + } + if (num >= 0) { + return Math.floor(num); + } +}; +var _default = exports.default = enforceRange; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/errors.js b/node_modules/fake-indexeddb/build/cjs/lib/errors.js new file mode 100644 index 0000000000000000000000000000000000000000..f30f2ce9a87fcada1c33d4b61bf078625fd3bd81 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/errors.js @@ -0,0 +1,100 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.VersionError = exports.TransactionInactiveError = exports.SyntaxError = exports.ReadOnlyError = exports.NotFoundError = exports.InvalidStateError = exports.InvalidAccessError = exports.DataError = exports.DataCloneError = exports.ConstraintError = exports.AbortError = void 0; +const messages = { + AbortError: "A request was aborted, for example through a call to IDBTransaction.abort.", + ConstraintError: "A mutation operation in the transaction failed because a constraint was not satisfied. For example, an object such as an object store or index already exists and a request attempted to create a new one.", + DataCloneError: "The data being stored could not be cloned by the internal structured cloning algorithm.", + DataError: "Data provided to an operation does not meet requirements.", + InvalidAccessError: "An invalid operation was performed on an object. For example transaction creation attempt was made, but an empty scope was provided.", + InvalidStateError: "An operation was called on an object on which it is not allowed or at a time when it is not allowed. Also occurs if a request is made on a source object that has been deleted or removed. Use TransactionInactiveError or ReadOnlyError when possible, as they are more specific variations of InvalidStateError.", + NotFoundError: "The operation failed because the requested database object could not be found. For example, an object store did not exist but was being opened.", + ReadOnlyError: 'The mutating operation was attempted in a "readonly" transaction.', + TransactionInactiveError: "A request was placed against a transaction which is currently not active, or which is finished.", + SyntaxError: "The keypath argument contains an invalid key path", + VersionError: "An attempt was made to open a database using a lower version than the existing version." +}; + +// Cannot set an error code on an error using the normal setter; +// this leads to "Cannot set property code of which has only a getter" +const setErrorCode = (error, value) => { + Object.defineProperty(error, 'code', { + value, + writable: false, + enumerable: true, + configurable: false + }); +}; +class AbortError extends DOMException { + constructor(message = messages.AbortError) { + super(message, "AbortError"); + } +} +exports.AbortError = AbortError; +class ConstraintError extends DOMException { + constructor(message = messages.ConstraintError) { + super(message, "ConstraintError"); + } +} +exports.ConstraintError = ConstraintError; +class DataCloneError extends DOMException { + constructor(message = messages.DataCloneError) { + super(message, "DataCloneError"); + } +} +exports.DataCloneError = DataCloneError; +class DataError extends DOMException { + constructor(message = messages.DataError) { + super(message, "DataError"); + setErrorCode(this, 0); + } +} +exports.DataError = DataError; +class InvalidAccessError extends DOMException { + constructor(message = messages.InvalidAccessError) { + super(message, "InvalidAccessError"); + } +} +exports.InvalidAccessError = InvalidAccessError; +class InvalidStateError extends DOMException { + constructor(message = messages.InvalidStateError) { + super(message, "InvalidStateError"); + setErrorCode(this, 11); + } +} +exports.InvalidStateError = InvalidStateError; +class NotFoundError extends DOMException { + constructor(message = messages.NotFoundError) { + super(message, "NotFoundError"); + } +} +exports.NotFoundError = NotFoundError; +class ReadOnlyError extends DOMException { + constructor(message = messages.ReadOnlyError) { + super(message, "ReadOnlyError"); + } +} +exports.ReadOnlyError = ReadOnlyError; +class SyntaxError extends DOMException { + constructor(message = messages.VersionError) { + super(message, "SyntaxError"); + setErrorCode(this, 12); + } +} +exports.SyntaxError = SyntaxError; +class TransactionInactiveError extends DOMException { + constructor(message = messages.TransactionInactiveError) { + super(message, "TransactionInactiveError"); + setErrorCode(this, 0); + } +} +exports.TransactionInactiveError = TransactionInactiveError; +class VersionError extends DOMException { + constructor(message = messages.VersionError) { + super(message, "VersionError"); + } +} +exports.VersionError = VersionError; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/extractGetAllOptions.js b/node_modules/fake-indexeddb/build/cjs/lib/extractGetAllOptions.js new file mode 100644 index 0000000000000000000000000000000000000000..93ea9a66f59d17c143681e3848e65947b665f56c --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/extractGetAllOptions.js @@ -0,0 +1,40 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _isPotentiallyValidKeyRange = _interopRequireDefault(require("./isPotentiallyValidKeyRange.js")); +var _enforceRange = _interopRequireDefault(require("./enforceRange.js")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +// https://www.w3.org/TR/IndexedDB/#create-request-to-retrieve-multiple-items +const extractGetAllOptions = (queryOrOptions, count, numArguments) => { + let query; + let direction; + if (queryOrOptions === undefined || queryOrOptions === null || (0, _isPotentiallyValidKeyRange.default)(queryOrOptions)) { + // queryOrOptions is FDBKeyRange | Key | null | undefined + query = queryOrOptions; + if (numArguments > 1 && count !== undefined) { + count = (0, _enforceRange.default)(count, "unsigned long"); + } + } else { + // queryOrOptions is FDBGetAllOptions + const getAllOptions = queryOrOptions; + if (getAllOptions.query !== undefined) { + query = getAllOptions.query; + } + if (getAllOptions.count !== undefined) { + count = (0, _enforceRange.default)(getAllOptions.count, "unsigned long"); + } + if (getAllOptions.direction !== undefined) { + direction = getAllOptions.direction; + } + } + return { + query, + count, + direction + }; +}; +var _default = exports.default = extractGetAllOptions; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/extractKey.js b/node_modules/fake-indexeddb/build/cjs/lib/extractKey.js new file mode 100644 index 0000000000000000000000000000000000000000..85c0d2b181038ed7840f4e07061a58f772d903f6 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/extractKey.js @@ -0,0 +1,61 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _valueToKey = _interopRequireDefault(require("./valueToKey.js")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-extracting-a-key-from-a-value-using-a-key-path +const extractKey = (keyPath, value) => { + if (Array.isArray(keyPath)) { + const result = []; + for (let item of keyPath) { + // This doesn't make sense to me based on the spec, but it is needed to pass the W3C KeyPath tests (see same + // comment in validateKeyPath) + if (item !== undefined && item !== null && typeof item !== "string" && item.toString) { + item = item.toString(); + } + const key = extractKey(item, value).key; + result.push((0, _valueToKey.default)(key)); + } + return { + type: "found", + key: result + }; + } + if (keyPath === "") { + return { + type: "found", + key: value + }; + } + let remainingKeyPath = keyPath; + let object = value; + while (remainingKeyPath !== null) { + let identifier; + const i = remainingKeyPath.indexOf("."); + if (i >= 0) { + identifier = remainingKeyPath.slice(0, i); + remainingKeyPath = remainingKeyPath.slice(i + 1); + } else { + identifier = remainingKeyPath; + remainingKeyPath = null; + } + + // special cases: https://w3c.github.io/IndexedDB/#evaluate-a-key-path-on-a-value + const isSpecialIdentifier = identifier === "length" && (typeof object === "string" || Array.isArray(object)) || (identifier === "size" || identifier === "type") && typeof Blob !== "undefined" && object instanceof Blob || (identifier === "name" || identifier === "lastModified") && typeof File !== "undefined" && object instanceof File; + if (!isSpecialIdentifier && (typeof object !== "object" || object === null || !Object.hasOwn(object, identifier))) { + return { + type: "notFound" + }; + } + object = object[identifier]; + } + return { + type: "found", + key: object + }; +}; +var _default = exports.default = extractKey; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/getKeyPath.js b/node_modules/fake-indexeddb/build/cjs/lib/getKeyPath.js new file mode 100644 index 0000000000000000000000000000000000000000..609a27c83ccf6e51d78f599d3be28c62e3473961 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/getKeyPath.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getKeyPath = getKeyPath; +// Keys provided as functions or arrays or objects need to be stringified +const convertKey = key => typeof key === 'object' && key ? key + '' : key; + +// https://www.w3.org/TR/IndexedDB/#dom-idbobjectstore-keypath +function getKeyPath(keyPath) { + // It's important to clone the Array here because of the WPT test: + // "Different instances are returned from different store instances." + // Also note that the same instance must be returned across multiple gets + return Array.isArray(keyPath) ? keyPath.map(convertKey) : convertKey(keyPath); +} \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/intersection.js b/node_modules/fake-indexeddb/build/cjs/lib/intersection.js new file mode 100644 index 0000000000000000000000000000000000000000..9ac13895ca72a9c077226086190723944d5b6c54 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/intersection.js @@ -0,0 +1,18 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.intersection = intersection; +/** + * Minimal polyfill of `Set.prototype.intersection`, available in Node 22+. + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/intersection + * @param set1 + * @param set2 + */ +function intersection(set1, set2) { + if ("intersection" in set1) { + return set1.intersection(set2); + } + return new Set([...set1].filter(item => set2.has(item))); +} \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/isPotentiallyValidKeyRange.js b/node_modules/fake-indexeddb/build/cjs/lib/isPotentiallyValidKeyRange.js new file mode 100644 index 0000000000000000000000000000000000000000..a378b78358952bdd2447f610582ae4670e998617 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/isPotentiallyValidKeyRange.js @@ -0,0 +1,26 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _FDBKeyRange = _interopRequireDefault(require("../FDBKeyRange.js")); +var _valueToKeyWithoutThrowing = _interopRequireWildcard(require("./valueToKeyWithoutThrowing.js")); +function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +// https://www.w3.org/TR/IndexedDB/#is-a-potentially-valid-key-range +const isPotentiallyValidKeyRange = value => { + // If value is a key range, return true. + if (value instanceof _FDBKeyRange.default) { + return true; + } + + // Let key be the result of converting a value to a key with value. + const key = (0, _valueToKeyWithoutThrowing.default)(value); + + // If key is "invalid type" return false. + // Else return true. + return key !== _valueToKeyWithoutThrowing.INVALID_TYPE; +}; +var _default = exports.default = isPotentiallyValidKeyRange; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/isSharedArrayBuffer.js b/node_modules/fake-indexeddb/build/cjs/lib/isSharedArrayBuffer.js new file mode 100644 index 0000000000000000000000000000000000000000..54062a28230ad2ac904ed10668da915198ee0c52 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/isSharedArrayBuffer.js @@ -0,0 +1,10 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isSharedArrayBuffer; +function isSharedArrayBuffer(input) { + return typeof SharedArrayBuffer !== "undefined" && input instanceof SharedArrayBuffer; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/scheduling.js b/node_modules/fake-indexeddb/build/cjs/lib/scheduling.js new file mode 100644 index 0000000000000000000000000000000000000000..4390406c2aa2744738b0bbe7783d5382bbc78cff --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/scheduling.js @@ -0,0 +1,46 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.queueTask = void 0; +// When running within Node.js (including jsdom), we want to use setImmediate +// (which runs immediately) rather than setTimeout (which enforces a minimum +// delay of 1ms, and on Windows only has a resolution of 15ms or so). jsdom +// doesn't provide setImmediate (to better match the browser environment) and +// sandboxes scripts, but its sandbox is by necessity imperfect, so we can break +// out of it: +// +// - https://github.com/jsdom/jsdom#executing-scripts +// - https://github.com/jsdom/jsdom/issues/2729 +// - https://github.com/scala-js/scala-js-macrotask-executor/pull/17 +function getSetImmediateFromJsdom() { + if (typeof navigator !== "undefined" && /jsdom/.test(navigator.userAgent)) { + const outerRealmFunctionConstructor = Node.constructor; + return new outerRealmFunctionConstructor("return setImmediate")(); + } else { + return undefined; + } +} + +// waiting on this PR for typescript types: https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1249 + +// 'postTask' runs right after microtasks, so equivalent to setTimeout but without the 4ms clamping. +// Using the default priority of 'user-visible' to avoid blocking input while still running fairly quickly. +// See: https://developer.mozilla.org/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#task_priorities +const schedulerPostTask = typeof scheduler !== "undefined" && (fn => scheduler.postTask(fn)); + +// fallback for environments that don't support any of the above +const doSetTimeout = fn => setTimeout(fn, 0); + +// Schedules a task to run later. Use Node.js's setImmediate if available and +// setTimeout otherwise. Note that options like process.nextTick or +// queueMicrotask will likely not work: IndexedDB semantics require that +// transactions are marked as not active when the event loop runs. The next +// tick queue and microtask queue run within the current event loop macrotask, +// so they'd process database operations too quickly. +const queueTask = fn => { + const setImmediate = globalThis.setImmediate || getSetImmediateFromJsdom() || schedulerPostTask || doSetTimeout; + setImmediate(fn); +}; +exports.queueTask = queueTask; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/types.js b/node_modules/fake-indexeddb/build/cjs/lib/types.js new file mode 100644 index 0000000000000000000000000000000000000000..9a390c31f71bc7eae1522a280a2dc8f6723185bf --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/types.js @@ -0,0 +1 @@ +"use strict"; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/validateKeyPath.js b/node_modules/fake-indexeddb/build/cjs/lib/validateKeyPath.js new file mode 100644 index 0000000000000000000000000000000000000000..2f9e7e8c552607a010bca9e650f4f3cb457a4c78 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/validateKeyPath.js @@ -0,0 +1,54 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _errors = require("./errors.js"); +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-valid-key-path +const validateKeyPath = (keyPath, parent) => { + // This doesn't make sense to me based on the spec, but it is needed to pass the W3C KeyPath tests (see same + // comment in extractKey) + if (keyPath !== undefined && keyPath !== null && typeof keyPath !== "string" && keyPath.toString && (parent === "array" || !Array.isArray(keyPath))) { + keyPath = keyPath.toString(); + } + if (typeof keyPath === "string") { + if (keyPath === "" && parent !== "string") { + return; + } + try { + // https://mathiasbynens.be/demo/javascript-identifier-regex for ECMAScript 5.1 / Unicode v7.0.0, with + // reserved words at beginning removed + const validIdentifierRegex = + // eslint-disable-next-line no-misleading-character-class + /^(?:[$A-Z_a-z\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\u08A0-\u08B2\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\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\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\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\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-\u13F4\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-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\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-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\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-\uAB5F\uAB64\uAB65\uABC0-\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])(?:[$0-9A-Z_a-z\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\u08A0-\u08B2\u08E4-\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\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-\u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DE6-\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-\u13F4\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\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\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\u200C\u200D\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-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\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-\uAB5F\uAB64\uAB65\uABC0-\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-\uFE2D\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])*$/; + if (keyPath.length >= 1 && validIdentifierRegex.test(keyPath)) { + return; + } + } catch (err) { + throw new _errors.SyntaxError(err.message); + } + if (keyPath.indexOf(" ") >= 0) { + throw new _errors.SyntaxError("The keypath argument contains an invalid key path (no spaces allowed)."); + } + } + if (Array.isArray(keyPath) && keyPath.length > 0) { + if (parent) { + // No nested arrays + throw new _errors.SyntaxError("The keypath argument contains an invalid key path (nested arrays)."); + } + for (const part of keyPath) { + validateKeyPath(part, "array"); + } + return; + } else if (typeof keyPath === "string" && keyPath.indexOf(".") >= 0) { + keyPath = keyPath.split("."); + for (const part of keyPath) { + validateKeyPath(part, "string"); + } + return; + } + throw new _errors.SyntaxError(); +}; +var _default = exports.default = validateKeyPath; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/validateRequiredArguments.js b/node_modules/fake-indexeddb/build/cjs/lib/validateRequiredArguments.js new file mode 100644 index 0000000000000000000000000000000000000000..868fc1a053e8a4c5f03090214c15fe8b041facb8 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/validateRequiredArguments.js @@ -0,0 +1,13 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.validateRequiredArguments = validateRequiredArguments; +// WebIDL requires passing the right number of non-optional arguments, e.g. IDBFactory.open() must have at least 1 arg +function validateRequiredArguments(numArguments, expectedNumArguments, methodName) { + if (numArguments < expectedNumArguments) { + // imitate Firefox's error message + throw new TypeError(`${methodName}: At least ${expectedNumArguments} ${expectedNumArguments === 1 ? "argument" : "arguments"} ` + `required, but only ${arguments.length} passed`); + } +} \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/valueToKey.js b/node_modules/fake-indexeddb/build/cjs/lib/valueToKey.js new file mode 100644 index 0000000000000000000000000000000000000000..354826009fd23fc6f332397d130ce92156d4da8c --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/valueToKey.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _errors = require("./errors.js"); +var _valueToKeyWithoutThrowing = _interopRequireWildcard(require("./valueToKeyWithoutThrowing.js")); +function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } +// https://w3c.github.io/IndexedDB/#convert-value-to-key +// Plus throwing a DataError for invalid value/invalid key, which is commonly done +// in lots of IndexedDB operations +const valueToKey = (input, seen) => { + const result = (0, _valueToKeyWithoutThrowing.default)(input, seen); + if (result === _valueToKeyWithoutThrowing.INVALID_VALUE || result === _valueToKeyWithoutThrowing.INVALID_TYPE) { + // If key is "invalid value" or "invalid type", throw a "DataError" DOMException + throw new _errors.DataError(); + } + return result; +}; +var _default = exports.default = valueToKey; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/valueToKeyRange.js b/node_modules/fake-indexeddb/build/cjs/lib/valueToKeyRange.js new file mode 100644 index 0000000000000000000000000000000000000000..e60be18d095bc3158febceebeaa796696c3cf942 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/valueToKeyRange.js @@ -0,0 +1,26 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _FDBKeyRange = _interopRequireDefault(require("../FDBKeyRange.js")); +var _errors = require("./errors.js"); +var _valueToKey = _interopRequireDefault(require("./valueToKey.js")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +// http://w3c.github.io/IndexedDB/#convert-a-value-to-a-key-range +const valueToKeyRange = (value, nullDisallowedFlag = false) => { + if (value instanceof _FDBKeyRange.default) { + return value; + } + if (value === null || value === undefined) { + if (nullDisallowedFlag) { + throw new _errors.DataError(); + } + return new _FDBKeyRange.default(undefined, undefined, false, false); + } + const key = (0, _valueToKey.default)(value); + return _FDBKeyRange.default.only(key); +}; +var _default = exports.default = valueToKeyRange; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/lib/valueToKeyWithoutThrowing.js b/node_modules/fake-indexeddb/build/cjs/lib/valueToKeyWithoutThrowing.js new file mode 100644 index 0000000000000000000000000000000000000000..2df74dbcc68ad40cd7d1fb4555599eaad4e06872 --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/lib/valueToKeyWithoutThrowing.js @@ -0,0 +1,102 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = exports.INVALID_VALUE = exports.INVALID_TYPE = void 0; +var _isSharedArrayBuffer = _interopRequireDefault(require("./isSharedArrayBuffer.js")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +const INVALID_TYPE = exports.INVALID_TYPE = Symbol("INVALID_TYPE"); +const INVALID_VALUE = exports.INVALID_VALUE = Symbol("INVALID_VALUE"); + +// https://w3c.github.io/IndexedDB/#convert-value-to-key +// The "without exceptions" version is because we typically want to throw exceptions (DataError) but not for +// the "is potentially valid key range" routine. +const valueToKeyWithoutThrowing = (input, seen) => { + if (typeof input === "number") { + if (isNaN(input)) { + // If input is NaN then return "invalid value". + return INVALID_VALUE; + } + return input; + } else if (Object.prototype.toString.call(input) === "[object Date]") { + const ms = input.valueOf(); + if (isNaN(ms)) { + // If ms is NaN then return "invalid value". + return INVALID_VALUE; + } + return new Date(ms); + } else if (typeof input === "string") { + return input; + } else if ( + // https://w3c.github.io/IndexedDB/#ref-for-dfn-buffer-source-type + input instanceof ArrayBuffer || (0, _isSharedArrayBuffer.default)(input) || typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView && ArrayBuffer.isView(input)) { + // We can't consistently test detachedness, so instead we check if byteLength === 0 + // This isn't foolproof, but there's no perfect way to detect if Uint8Arrays or + // SharedArrayBuffers are detached + if ("detached" in input ? input.detached : input.byteLength === 0) { + // If input is detached then return "invalid value". + return INVALID_VALUE; + } + let arrayBuffer; + let offset = 0; + let length = 0; + if (input instanceof ArrayBuffer || (0, _isSharedArrayBuffer.default)(input)) { + arrayBuffer = input; + length = input.byteLength; + } else { + arrayBuffer = input.buffer; + offset = input.byteOffset; + length = input.byteLength; + } + return arrayBuffer.slice(offset, offset + length); + } else if (Array.isArray(input)) { + if (seen === undefined) { + seen = new Set(); + } else if (seen.has(input)) { + // If seen contains input, then return "invalid value". + return INVALID_VALUE; + } + seen.add(input); + + // This algorithm is tricky to account for `bindings-inject-keys-bypass.any.js`. We _should_ return early when + // encountering an invalid key/type, but we also need to avoid triggering `Object.prototype['10']` if it's been + // overridden. One simple way to do this (and which doesn't rely on sparse arrays or other exotic solutions that + // could cause de-opts) is to use `Array.from()` with a mapper function, which does not trigger the prototype + // setter [1]. It does prevent an early return, but we can at least short-circuit inside the mapper function + // (which isn't strictly necessary to pass the WPTs, but is closer to the spec). + // [1]: See https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.from, specifically + // the chain CreateDataPropertyOrThrow -> CreateDataProperty -> DefineOwnProperty which defines + // the array element as an "own" property. + let hasInvalid = false; + const keys = Array.from({ + length: input.length + }, (_, i) => { + if (hasInvalid) { + return; + } + const hop = Object.hasOwn(input, i); + if (!hop) { + // If hop is false, return "invalid value". + hasInvalid = true; + return; + } + const entry = input[i]; + const key = valueToKeyWithoutThrowing(entry, seen); + // If key is "invalid value" or "invalid type" abort these steps and return "invalid value". + if (key === INVALID_VALUE || key === INVALID_TYPE) { + hasInvalid = true; + return; + } + return key; + }); + if (hasInvalid) { + return INVALID_VALUE; + } + return keys; + } else { + // Otherwise: Return "invalid type". + return INVALID_TYPE; + } +}; +var _default = exports.default = valueToKeyWithoutThrowing; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/cjs/package.json b/node_modules/fake-indexeddb/build/cjs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..729ac4d93b7f2d9be36b44525f02ff6555f9383a --- /dev/null +++ b/node_modules/fake-indexeddb/build/cjs/package.json @@ -0,0 +1 @@ +{"type":"commonjs"} diff --git a/node_modules/fake-indexeddb/build/esm/FDBCursor.js b/node_modules/fake-indexeddb/build/esm/FDBCursor.js new file mode 100644 index 0000000000000000000000000000000000000000..58c722b72bd0589f95c9f9ade9d1213d3451c887 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/FDBCursor.js @@ -0,0 +1,472 @@ +import FDBKeyRange from "./FDBKeyRange.js"; +import FDBObjectStore from "./FDBObjectStore.js"; +import cmp from "./lib/cmp.js"; +import { DataError, InvalidAccessError, InvalidStateError, ReadOnlyError, TransactionInactiveError } from "./lib/errors.js"; +import extractKey from "./lib/extractKey.js"; +import valueToKey from "./lib/valueToKey.js"; +import { cloneValueForInsertion } from "./lib/cloneValueForInsertion.js"; +const getEffectiveObjectStore = cursor => { + if (cursor.source instanceof FDBObjectStore) { + return cursor.source; + } + return cursor.source.objectStore; +}; + +// This takes a key range, a list of lower bounds, and a list of upper bounds and combines them all into a single key +// range. It does not handle gt/gte distinctions, because it doesn't really matter much anyway, since for next/prev +// cursor iteration it'd also have to look at values to be precise, which would be complicated. This should get us 99% +// of the way there. +const makeKeyRange = (range, lowers, uppers) => { + // Start with bounds from range + let lower = range !== undefined ? range.lower : undefined; + let upper = range !== undefined ? range.upper : undefined; + + // Augment with values from lowers and uppers + for (const lowerTemp of lowers) { + if (lowerTemp === undefined) { + continue; + } + if (lower === undefined || cmp(lower, lowerTemp) === 1) { + lower = lowerTemp; + } + } + for (const upperTemp of uppers) { + if (upperTemp === undefined) { + continue; + } + if (upper === undefined || cmp(upper, upperTemp) === -1) { + upper = upperTemp; + } + } + if (lower !== undefined && upper !== undefined) { + return FDBKeyRange.bound(lower, upper); + } + if (lower !== undefined) { + return FDBKeyRange.lowerBound(lower); + } + if (upper !== undefined) { + return FDBKeyRange.upperBound(upper); + } +}; + +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#cursor +class FDBCursor { + _gotValue = false; + _position = undefined; // Key of previously returned record + _objectStorePosition = undefined; + _keyOnly = false; + _key = undefined; + _primaryKey = undefined; + constructor(source, range, direction = "next", request, keyOnly = false) { + this._range = range; + this._source = source; + this._direction = direction; + this._request = request; + this._keyOnly = keyOnly; + } + + // Read only properties + get source() { + return this._source; + } + set source(val) { + /* For babel */ + } + get request() { + return this._request; + } + set request(val) { + /* For babel */ + } + get direction() { + return this._direction; + } + set direction(val) { + /* For babel */ + } + get key() { + return this._key; + } + set key(val) { + /* For babel */ + } + get primaryKey() { + return this._primaryKey; + } + set primaryKey(val) { + /* For babel */ + } + + // https://w3c.github.io/IndexedDB/#iterate-a-cursor + _iterate(key, primaryKey) { + const sourceIsObjectStore = this.source instanceof FDBObjectStore; + + // Can't use sourceIsObjectStore because TypeScript + const records = this.source instanceof FDBObjectStore ? this.source._rawObjectStore.records : this.source._rawIndex.records; + let foundRecord; + if (this.direction === "next") { + const range = makeKeyRange(this._range, [key, this._position], []); + for (const record of records.values(range)) { + const cmpResultKey = key !== undefined ? cmp(record.key, key) : undefined; + const cmpResultPosition = this._position !== undefined ? cmp(record.key, this._position) : undefined; + if (key !== undefined) { + if (cmpResultKey === -1) { + continue; + } + } + if (primaryKey !== undefined) { + if (cmpResultKey === -1) { + continue; + } + const cmpResultPrimaryKey = cmp(record.value, primaryKey); + if (cmpResultKey === 0 && cmpResultPrimaryKey === -1) { + continue; + } + } + if (this._position !== undefined && sourceIsObjectStore) { + if (cmpResultPosition !== 1) { + continue; + } + } + if (this._position !== undefined && !sourceIsObjectStore) { + if (cmpResultPosition === -1) { + continue; + } + if (cmpResultPosition === 0 && cmp(record.value, this._objectStorePosition) !== 1) { + continue; + } + } + if (this._range !== undefined) { + if (!this._range.includes(record.key)) { + continue; + } + } + foundRecord = record; + break; + } + } else if (this.direction === "nextunique") { + // This could be done without iterating, if the range was defined slightly better (to handle gt/gte cases). + // But the performance difference should be small, and that wouldn't work anyway for directions where the + // value needs to be used (like next and prev). + const range = makeKeyRange(this._range, [key, this._position], []); + for (const record of records.values(range)) { + if (key !== undefined) { + if (cmp(record.key, key) === -1) { + continue; + } + } + if (this._position !== undefined) { + if (cmp(record.key, this._position) !== 1) { + continue; + } + } + if (this._range !== undefined) { + if (!this._range.includes(record.key)) { + continue; + } + } + foundRecord = record; + break; + } + } else if (this.direction === "prev") { + const range = makeKeyRange(this._range, [], [key, this._position]); + for (const record of records.values(range, "prev")) { + const cmpResultKey = key !== undefined ? cmp(record.key, key) : undefined; + const cmpResultPosition = this._position !== undefined ? cmp(record.key, this._position) : undefined; + if (key !== undefined) { + if (cmpResultKey === 1) { + continue; + } + } + if (primaryKey !== undefined) { + if (cmpResultKey === 1) { + continue; + } + const cmpResultPrimaryKey = cmp(record.value, primaryKey); + if (cmpResultKey === 0 && cmpResultPrimaryKey === 1) { + continue; + } + } + if (this._position !== undefined && sourceIsObjectStore) { + if (cmpResultPosition !== -1) { + continue; + } + } + if (this._position !== undefined && !sourceIsObjectStore) { + if (cmpResultPosition === 1) { + continue; + } + if (cmpResultPosition === 0 && cmp(record.value, this._objectStorePosition) !== -1) { + continue; + } + } + if (this._range !== undefined) { + if (!this._range.includes(record.key)) { + continue; + } + } + foundRecord = record; + break; + } + } else if (this.direction === "prevunique") { + let tempRecord; + const range = makeKeyRange(this._range, [], [key, this._position]); + for (const record of records.values(range, "prev")) { + if (key !== undefined) { + if (cmp(record.key, key) === 1) { + continue; + } + } + if (this._position !== undefined) { + if (cmp(record.key, this._position) !== -1) { + continue; + } + } + if (this._range !== undefined) { + if (!this._range.includes(record.key)) { + continue; + } + } + tempRecord = record; + break; + } + if (tempRecord) { + foundRecord = records.get(tempRecord.key); + } + } + let result; + if (!foundRecord) { + this._key = undefined; + if (!sourceIsObjectStore) { + this._objectStorePosition = undefined; + } + + // "this instanceof FDBCursorWithValue" would be better and not require (this as any), but causes runtime + // error due to circular dependency. + if (!this._keyOnly && this.toString() === "[object IDBCursorWithValue]") { + this.value = undefined; + } + result = null; + } else { + this._position = foundRecord.key; + if (!sourceIsObjectStore) { + this._objectStorePosition = foundRecord.value; + } + this._key = foundRecord.key; + if (sourceIsObjectStore) { + this._primaryKey = structuredClone(foundRecord.key); + if (!this._keyOnly && this.toString() === "[object IDBCursorWithValue]") { + this.value = structuredClone(foundRecord.value); + } + } else { + this._primaryKey = structuredClone(foundRecord.value); + if (!this._keyOnly && this.toString() === "[object IDBCursorWithValue]") { + if (this.source instanceof FDBObjectStore) { + // Can't use sourceIsObjectStore because TypeScript + throw new Error("This should never happen"); + } + const value = this.source.objectStore._rawObjectStore.getValue(foundRecord.value); + this.value = structuredClone(value); + } + } + this._gotValue = true; + // eslint-disable-next-line @typescript-eslint/no-this-alias + result = this; + } + return result; + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBCursor-update-IDBRequest-any-value + update(value) { + if (value === undefined) { + throw new TypeError(); + } + const effectiveObjectStore = getEffectiveObjectStore(this); + const effectiveKey = Object.hasOwn(this.source, "_rawIndex") ? this.primaryKey : this._position; + const transaction = effectiveObjectStore.transaction; + if (transaction._state !== "active") { + throw new TransactionInactiveError(); + } + if (transaction.mode === "readonly") { + throw new ReadOnlyError(); + } + if (effectiveObjectStore._rawObjectStore.deleted) { + throw new InvalidStateError(); + } + if (!(this.source instanceof FDBObjectStore) && this.source._rawIndex.deleted) { + throw new InvalidStateError(); + } + if (!this._gotValue || !Object.hasOwn(this, "value")) { + throw new InvalidStateError(); + } + const clone = cloneValueForInsertion(value, transaction); + if (effectiveObjectStore.keyPath !== null) { + let tempKey; + try { + tempKey = extractKey(effectiveObjectStore.keyPath, clone).key; + } catch (err) { + /* Handled immediately below */ + } + if (cmp(tempKey, effectiveKey) !== 0) { + throw new DataError(); + } + } + const record = { + key: effectiveKey, + value: clone + }; + return transaction._execRequestAsync({ + operation: effectiveObjectStore._rawObjectStore.storeRecord.bind(effectiveObjectStore._rawObjectStore, record, false, transaction._rollbackLog), + source: this + }); + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBCursor-advance-void-unsigned-long-count + advance(count) { + if (!Number.isInteger(count) || count <= 0) { + throw new TypeError(); + } + const effectiveObjectStore = getEffectiveObjectStore(this); + const transaction = effectiveObjectStore.transaction; + if (transaction._state !== "active") { + throw new TransactionInactiveError(); + } + if (effectiveObjectStore._rawObjectStore.deleted) { + throw new InvalidStateError(); + } + if (!(this.source instanceof FDBObjectStore) && this.source._rawIndex.deleted) { + throw new InvalidStateError(); + } + if (!this._gotValue) { + throw new InvalidStateError(); + } + if (this._request) { + this._request.readyState = "pending"; + } + transaction._execRequestAsync({ + operation: () => { + let result; + for (let i = 0; i < count; i++) { + result = this._iterate(); + + // Not sure why this is needed + if (!result) { + break; + } + } + return result; + }, + request: this._request, + source: this.source + }); + this._gotValue = false; + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBCursor-continue-void-any-key + continue(key) { + const effectiveObjectStore = getEffectiveObjectStore(this); + const transaction = effectiveObjectStore.transaction; + if (transaction._state !== "active") { + throw new TransactionInactiveError(); + } + if (effectiveObjectStore._rawObjectStore.deleted) { + throw new InvalidStateError(); + } + if (!(this.source instanceof FDBObjectStore) && this.source._rawIndex.deleted) { + throw new InvalidStateError(); + } + if (!this._gotValue) { + throw new InvalidStateError(); + } + if (key !== undefined) { + key = valueToKey(key); + const cmpResult = cmp(key, this._position); + if (cmpResult <= 0 && (this.direction === "next" || this.direction === "nextunique") || cmpResult >= 0 && (this.direction === "prev" || this.direction === "prevunique")) { + throw new DataError(); + } + } + if (this._request) { + this._request.readyState = "pending"; + } + transaction._execRequestAsync({ + operation: this._iterate.bind(this, key), + request: this._request, + source: this.source + }); + this._gotValue = false; + } + + // hthttps://w3c.github.io/IndexedDB/#dom-idbcursor-continueprimarykey + continuePrimaryKey(key, primaryKey) { + const effectiveObjectStore = getEffectiveObjectStore(this); + const transaction = effectiveObjectStore.transaction; + if (transaction._state !== "active") { + throw new TransactionInactiveError(); + } + if (effectiveObjectStore._rawObjectStore.deleted) { + throw new InvalidStateError(); + } + if (!(this.source instanceof FDBObjectStore) && this.source._rawIndex.deleted) { + throw new InvalidStateError(); + } + if (this.source instanceof FDBObjectStore || this.direction !== "next" && this.direction !== "prev") { + throw new InvalidAccessError(); + } + if (!this._gotValue) { + throw new InvalidStateError(); + } + + // Not sure about this + if (key === undefined || primaryKey === undefined) { + throw new DataError(); + } + key = valueToKey(key); + const cmpResult = cmp(key, this._position); + if (cmpResult === -1 && this.direction === "next" || cmpResult === 1 && this.direction === "prev") { + throw new DataError(); + } + const cmpResult2 = cmp(primaryKey, this._objectStorePosition); + if (cmpResult === 0) { + if (cmpResult2 <= 0 && this.direction === "next" || cmpResult2 >= 0 && this.direction === "prev") { + throw new DataError(); + } + } + if (this._request) { + this._request.readyState = "pending"; + } + transaction._execRequestAsync({ + operation: this._iterate.bind(this, key, primaryKey), + request: this._request, + source: this.source + }); + this._gotValue = false; + } + delete() { + const effectiveObjectStore = getEffectiveObjectStore(this); + const effectiveKey = Object.hasOwn(this.source, "_rawIndex") ? this.primaryKey : this._position; + const transaction = effectiveObjectStore.transaction; + if (transaction._state !== "active") { + throw new TransactionInactiveError(); + } + if (transaction.mode === "readonly") { + throw new ReadOnlyError(); + } + if (effectiveObjectStore._rawObjectStore.deleted) { + throw new InvalidStateError(); + } + if (!(this.source instanceof FDBObjectStore) && this.source._rawIndex.deleted) { + throw new InvalidStateError(); + } + if (!this._gotValue || !Object.hasOwn(this, "value")) { + throw new InvalidStateError(); + } + return transaction._execRequestAsync({ + operation: effectiveObjectStore._rawObjectStore.deleteRecord.bind(effectiveObjectStore._rawObjectStore, effectiveKey, transaction._rollbackLog), + source: this + }); + } + get [Symbol.toStringTag]() { + return "IDBCursor"; + } +} +export default FDBCursor; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/FDBCursorWithValue.js b/node_modules/fake-indexeddb/build/esm/FDBCursorWithValue.js new file mode 100644 index 0000000000000000000000000000000000000000..a18c02790cd37fd84c9b0fdfd4e916a11789572b --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/FDBCursorWithValue.js @@ -0,0 +1,11 @@ +import FDBCursor from "./FDBCursor.js"; +class FDBCursorWithValue extends FDBCursor { + value = undefined; + constructor(source, range, direction, request) { + super(source, range, direction, request); + } + get [Symbol.toStringTag]() { + return "IDBCursorWithValue"; + } +} +export default FDBCursorWithValue; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/FDBDatabase.js b/node_modules/fake-indexeddb/build/esm/FDBDatabase.js new file mode 100644 index 0000000000000000000000000000000000000000..59a8a9d49a446c9602b313aac840bf0c2100bb7d --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/FDBDatabase.js @@ -0,0 +1,171 @@ +import FDBTransaction from "./FDBTransaction.js"; +import { ConstraintError, InvalidAccessError, InvalidStateError, NotFoundError, TransactionInactiveError } from "./lib/errors.js"; +import FakeDOMStringList from "./lib/FakeDOMStringList.js"; +import FakeEventTarget from "./lib/FakeEventTarget.js"; +import ObjectStore from "./lib/ObjectStore.js"; +import validateKeyPath from "./lib/validateKeyPath.js"; +import closeConnection from "./lib/closeConnection.js"; +// Common first 3 steps of https://www.w3.org/TR/IndexedDB/#dom-idbdatabase-createobjectstore and https://www.w3.org/TR/IndexedDB/#dom-idbdatabase-deleteobjectstore +const confirmActiveVersionchangeTransaction = database => { + // Let transaction be database’s upgrade transaction if it is not null, or throw an "InvalidStateError" DOMException otherwise. + let transaction; + if (database._runningVersionchangeTransaction) { + // Find the latest versionchange transaction + transaction = database._rawDatabase.transactions.findLast(tx => { + return tx.mode === "versionchange"; + }); + } + if (!transaction) { + throw new InvalidStateError(); + } + + // If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException. + if (transaction._state !== "active") { + throw new TransactionInactiveError(); + } + return transaction; +}; + +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#database-interface +class FDBDatabase extends FakeEventTarget { + _closePending = false; + _closed = false; + _runningVersionchangeTransaction = false; + constructor(rawDatabase) { + super(); + this._rawDatabase = rawDatabase; + this._rawDatabase.connections.push(this); + this.name = rawDatabase.name; + this.version = rawDatabase.version; + this.objectStoreNames = new FakeDOMStringList(...Array.from(rawDatabase.rawObjectStores.keys()).sort()); + } + + // http://w3c.github.io/IndexedDB/#dom-idbdatabase-createobjectstore + createObjectStore(name, options = {}) { + if (name === undefined) { + throw new TypeError(); + } + const transaction = confirmActiveVersionchangeTransaction(this); + const keyPath = options !== null && options.keyPath !== undefined ? options.keyPath : null; + const autoIncrement = options !== null && options.autoIncrement !== undefined ? options.autoIncrement : false; + if (keyPath !== null) { + validateKeyPath(keyPath); + } + if (this._rawDatabase.rawObjectStores.has(name)) { + throw new ConstraintError(); + } + if (autoIncrement && (keyPath === "" || Array.isArray(keyPath))) { + throw new InvalidAccessError(); + } + + // Save for rollbackLog + const objectStoreNames = [...this.objectStoreNames]; + const transactionObjectStoreNames = [...transaction.objectStoreNames]; + const rawObjectStore = new ObjectStore(this._rawDatabase, name, keyPath, autoIncrement); + this.objectStoreNames._push(name); + this.objectStoreNames._sort(); + transaction._scope.add(name); + transaction._createdObjectStores.add(rawObjectStore); + this._rawDatabase.rawObjectStores.set(name, rawObjectStore); + transaction.objectStoreNames = new FakeDOMStringList(...this.objectStoreNames); + transaction._rollbackLog.push(() => { + rawObjectStore.deleted = true; + this.objectStoreNames = new FakeDOMStringList(...objectStoreNames); + transaction.objectStoreNames = new FakeDOMStringList(...transactionObjectStoreNames); + transaction._scope.delete(rawObjectStore.name); + this._rawDatabase.rawObjectStores.delete(rawObjectStore.name); + }); + return transaction.objectStore(name); + } + + // https://www.w3.org/TR/IndexedDB/#dom-idbdatabase-deleteobjectstore + deleteObjectStore(name) { + if (name === undefined) { + throw new TypeError(); + } + const transaction = confirmActiveVersionchangeTransaction(this); + + // Let store be the object store named name in database, or throw a "NotFoundError" DOMException if none. + const store = this._rawDatabase.rawObjectStores.get(name); + if (store === undefined) { + throw new NotFoundError(); + } + + // Remove store from this’s object store set. + // This method synchronously modifies the objectStoreNames property on the IDBDatabase instance on which it was called. + this.objectStoreNames = new FakeDOMStringList(...Array.from(this.objectStoreNames).filter(objectStoreName => { + return objectStoreName !== name; + })); + transaction.objectStoreNames = new FakeDOMStringList(...this.objectStoreNames); + + // If there is an object store handle associated with store and transaction, remove all entries from its index set. + const objectStore = transaction._objectStoresCache.get(name); + let prevIndexNames; + if (objectStore) { + prevIndexNames = [...objectStore.indexNames]; + objectStore.indexNames = new FakeDOMStringList(); + } + transaction._rollbackLog.push(() => { + store.deleted = false; + this._rawDatabase.rawObjectStores.set(store.name, store); + this.objectStoreNames._push(store.name); + transaction.objectStoreNames._push(store.name); + this.objectStoreNames._sort(); + if (objectStore && prevIndexNames) { + objectStore.indexNames = new FakeDOMStringList(...prevIndexNames); + } + }); + + // Destroy store. + store.deleted = true; + this._rawDatabase.rawObjectStores.delete(name); + transaction._objectStoresCache.delete(name); + } + transaction(storeNames, mode, options) { + mode = mode !== undefined ? mode : "readonly"; + if (mode !== "readonly" && mode !== "readwrite" && mode !== "versionchange") { + throw new TypeError("Invalid mode: " + mode); + } + const hasActiveVersionchange = this._rawDatabase.transactions.some(transaction => { + return transaction._state === "active" && transaction.mode === "versionchange" && transaction.db === this; + }); + if (hasActiveVersionchange) { + throw new InvalidStateError(); + } + if (this._closePending) { + throw new InvalidStateError(); + } + if (!Array.isArray(storeNames)) { + storeNames = [storeNames]; + } + if (storeNames.length === 0 && mode !== "versionchange") { + throw new InvalidAccessError(); + } + for (const storeName of storeNames) { + if (!this.objectStoreNames.contains(storeName)) { + throw new NotFoundError("No objectStore named " + storeName + " in this database"); + } + } + + // the actual algo is more complex but this passes the IDB tests: https://webidl.spec.whatwg.org/#es-dictionary + const durability = options?.durability ?? "default"; + // invalid enums throw a TypeError: https://webidl.spec.whatwg.org/#es-enumeration + if (durability !== "default" && durability !== "strict" && durability !== "relaxed") { + throw new TypeError( + // based on Firefox's error message + `'${durability}' (value of 'durability' member of IDBTransactionOptions) ` + `is not a valid value for enumeration IDBTransactionDurability`); + } + const tx = new FDBTransaction(storeNames, mode, durability, this); + this._rawDatabase.transactions.push(tx); + this._rawDatabase.processTransactions(); // See if can start right away (async) + + return tx; + } + close() { + closeConnection(this); + } + get [Symbol.toStringTag]() { + return "IDBDatabase"; + } +} +export default FDBDatabase; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/FDBFactory.js b/node_modules/fake-indexeddb/build/esm/FDBFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..12f11c2feb1555036c555e29bd021ee8323d96b8 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/FDBFactory.js @@ -0,0 +1,406 @@ +import FDBDatabase from "./FDBDatabase.js"; +import FDBOpenDBRequest from "./FDBOpenDBRequest.js"; +import FDBVersionChangeEvent from "./FDBVersionChangeEvent.js"; +import cmp from "./lib/cmp.js"; +import Database from "./lib/Database.js"; +import enforceRange from "./lib/enforceRange.js"; +import { AbortError, VersionError } from "./lib/errors.js"; +import FakeEvent from "./lib/FakeEvent.js"; +import { queueTask } from "./lib/scheduling.js"; +import { validateRequiredArguments } from "./lib/validateRequiredArguments.js"; +// https://w3c.github.io/IndexedDB/#connection-queue +const runTaskInConnectionQueue = (connectionQueues, name, task) => { + // Let queue be the connection queue for storageKey and name. + // (note FakeIndexedDB does not support storageKeys currently) + // Add request to queue. + // Wait until all previous requests in queue have been processed. + const queue = connectionQueues.get(name) ?? Promise.resolve(); + connectionQueues.set(name, queue.then(task)); +}; +const waitForOthersClosedDelete = (databases, name, openDatabases, cb) => { + const anyOpen = openDatabases.some(openDatabase2 => { + return !openDatabase2._closed && !openDatabase2._closePending; + }); + if (anyOpen) { + queueTask(() => waitForOthersClosedDelete(databases, name, openDatabases, cb)); + return; + } + databases.delete(name); + cb(null); +}; + +// https://w3c.github.io/IndexedDB/#delete-a-database +const deleteDatabase = (databases, connectionQueues, name, request, cb) => { + const deleteDBTask = () => { + return new Promise(resolve => { + const db = databases.get(name); + const oldVersion = db !== undefined ? db.version : 0; + const onComplete = err => { + try { + if (err) { + cb(err); + } else { + cb(null, oldVersion); + } + } finally { + resolve(); + } + }; + try { + const db = databases.get(name); + if (db === undefined) { + onComplete(null); + return; + } + + // Let openConnections be the set of all connections associated with db. + const openConnections = db.connections.filter(connection => { + return !connection._closed; + }); + + // For each entry of openConnections that does not have its close pending flag set to true, queue a + // database task to fire a version change event named versionchange at entry with db’s version and null. + for (const openDatabase2 of openConnections) { + if (!openDatabase2._closePending) { + queueTask(() => { + const event = new FDBVersionChangeEvent("versionchange", { + newVersion: null, + oldVersion: db.version + }); + openDatabase2.dispatchEvent(event); + }); + } + } + + // Wait for all of the events to be fired. (i.e. queue a task) + queueTask(() => { + // If any of the connections in openConnections are still not closed, queue a database task to + // fire a version change event named blocked at request with db’s version and null. + + const anyOpen = openConnections.some(openDatabase3 => { + return !openDatabase3._closed && !openDatabase3._closePending; + }); + + // If any of the connections in openConnections are still not closed, queue a database task to + // fire a version change event named blocked at request with db’s version and null. + if (anyOpen) { + queueTask(() => { + const event = new FDBVersionChangeEvent("blocked", { + newVersion: null, + oldVersion: db.version + }); + request.dispatchEvent(event); + }); + } + + // Wait until all connections in openConnections are closed. + waitForOthersClosedDelete(databases, name, openConnections, onComplete); + }); + } catch (err) { + onComplete(err); + } + }); + }; + runTaskInConnectionQueue(connectionQueues, name, deleteDBTask); +}; + +// https://w3c.github.io/IndexedDB/#ref-for-database-version%E2%91%A0%E2%91%A2 +const runVersionchangeTransaction = (connection, version, request, cb) => { + connection._runningVersionchangeTransaction = true; + const oldVersion = connection._oldVersion = connection.version; + + // Let openConnections be the set of all connections, except connection, associated with db. + const openConnections = connection._rawDatabase.connections.filter(otherDatabase => { + return connection !== otherDatabase; + }); + + // For each entry of openConnections that does not have its close pending flag set to true, queue a + // database task to fire a version change event named versionchange at entry with db’s version and version. + for (const openDatabase2 of openConnections) { + if (!openDatabase2._closed && !openDatabase2._closePending) { + queueTask(() => { + const event = new FDBVersionChangeEvent("versionchange", { + newVersion: version, + oldVersion + }); + openDatabase2.dispatchEvent(event); + }); + } + } + + // Wait for all of the events to be fired. + // (i.e. queue a task) + queueTask(() => { + const anyOpen = openConnections.some(openDatabase3 => { + return !openDatabase3._closed && !openDatabase3._closePending; + }); + + // If any of the connections in openConnections are still not closed, queue a database task to fire a version change event named blocked at request with db’s version and version. + if (anyOpen) { + queueTask(() => { + const event = new FDBVersionChangeEvent("blocked", { + newVersion: version, + oldVersion + }); + request.dispatchEvent(event); + }); + } + + // Wait until all connections in openConnections are closed. + const waitForOthersClosed = () => { + const anyOpen2 = openConnections.some(openDatabase2 => { + return !openDatabase2._closed && !openDatabase2._closePending; + }); + if (anyOpen2) { + queueTask(waitForOthersClosed); + return; + } + + // Set the version of database to version. This change is considered part of the transaction, and so if the + // transaction is aborted, this change is reverted. + connection._rawDatabase.version = version; + connection.version = version; + + // Get rid of this setImmediate? + const transaction = connection.transaction(Array.from(connection.objectStoreNames), "versionchange"); + + // associate the transaction with the open request for later lookup + transaction._openRequest = request; + + // https://w3c.github.io/IndexedDB/#upgrade-a-database + // Set request’s result to connection. + request.result = connection; + // Set request’s done flag to true. + request.readyState = "done"; + // Set request’s transaction to transaction. + request.transaction = transaction; + transaction._rollbackLog.push(() => { + connection._rawDatabase.version = oldVersion; + connection.version = oldVersion; + }); + + // Set transaction’s state to active. + transaction._state = "active"; + + // Let didThrow be the result of firing a version change event named upgradeneeded at request with old version and version. + const event = new FDBVersionChangeEvent("upgradeneeded", { + newVersion: version, + oldVersion + }); + let didThrow = false; + try { + request.dispatchEvent(event); + } catch (_err) { + didThrow = true; + } + const concludeUpgrade = () => { + // If transaction’s state is active, then: + if (transaction._state === "active") { + // Set transaction’s state to inactive. + transaction._state = "inactive"; + if (didThrow) { + // If didThrow is true, run abort a transaction with transaction and a newly created "AbortError" DOMException. + transaction._abort("AbortError"); + } + } + }; + + // The "upgrade a database" steps are supposed to run as a database task on the database access task source + // (i.e. off the main thread), but since we're actually running on the main thread, we have to be tricky: + // 1. If any `upgradeneeded` event handlers errored, abort synchronously + // 2. Else yield to allow any microtasks to run in response to that event + if (didThrow) { + concludeUpgrade(); + } else { + queueTask(concludeUpgrade); + } + transaction._prioritizedListeners.set("error", () => { + connection._runningVersionchangeTransaction = false; + connection._oldVersion = undefined; + // throw arguments[0].target.error; + // console.log("error in versionchange transaction - not sure if anything needs to be done here", e.target.error.name); + }); + transaction._prioritizedListeners.set("abort", () => { + connection._runningVersionchangeTransaction = false; + connection._oldVersion = undefined; + queueTask(() => { + // Reset transaction in a tick after onabort (upgrade-transaction-lifecycle-user-aborted.any) + request.transaction = null; + cb(new AbortError()); + }); + }); + transaction._prioritizedListeners.set("complete", () => { + connection._runningVersionchangeTransaction = false; + connection._oldVersion = undefined; + // Let other complete event handlers run before continuing + queueTask(() => { + // Reset transaction in a tick after oncomplete (upgrade-transaction-lifecycle-committed.any.js) + request.transaction = null; + if (connection._closePending) { + cb(new AbortError()); + } else { + cb(null); + } + }); + }); + }; + waitForOthersClosed(); + }); +}; + +// https://w3c.github.io/IndexedDB/#opening +const openDatabase = (databases, connectionQueues, name, version, request, cb) => { + const openDBTask = () => { + return new Promise(resolve => { + const onComplete = err => { + try { + if (err) { + // DO THIS HERE: ensure that connection is closed by running the steps for closing a database connection before these + // steps are aborted. + cb(err); + } else { + cb(null, connection); + } + } finally { + resolve(); + } + }; + + // Let db be the database named name in storageKey, or null otherwise. + let db = databases.get(name); + if (db === undefined) { + // If db is null, let db be a new database with name `name`, version 0 (zero), and with no object stores. + db = new Database(name, 0); + databases.set(name, db); + } + + // If version is undefined, let version be 1 if db is null, or db’s version otherwise. + if (version === undefined) { + version = db.version !== 0 ? db.version : 1; + } + + // If db’s version is greater than version, return a newly created "VersionError" DOMException and abort these steps. + if (db.version > version) { + return onComplete(new VersionError()); + } + + // Let connection be a new connection to db. + const connection = new FDBDatabase(db); + + // If db’s version is less than version, then: + if (db.version < version) { + // (run a version change transaction and resolve so that the next promise in the queue will execute) + runVersionchangeTransaction(connection, version, request, err => { + onComplete(err); + }); + } else { + onComplete(null); + } + }); + }; + runTaskInConnectionQueue(connectionQueues, name, openDBTask); +}; +class FDBFactory { + _databases = new Map(); + // https://w3c.github.io/IndexedDB/#connection-queue + _connectionQueues = new Map(); // promise chain as lightweight FIFO task queue + + // https://w3c.github.io/IndexedDB/#dom-idbfactory-cmp + cmp(first, second) { + validateRequiredArguments(arguments.length, 2, "IDBFactory.cmp"); + return cmp(first, second); + } + + // https://w3c.github.io/IndexedDB/#dom-idbfactory-deletedatabase + deleteDatabase(name) { + validateRequiredArguments(arguments.length, 1, "IDBFactory.deleteDatabase"); + const request = new FDBOpenDBRequest(); + request.source = null; + queueTask(() => { + deleteDatabase(this._databases, this._connectionQueues, name, request, (err, oldVersion) => { + if (err) { + request.error = new DOMException(err.message, err.name); + request.readyState = "done"; + const event = new FakeEvent("error", { + bubbles: true, + cancelable: true + }); + event.eventPath = []; + request.dispatchEvent(event); + return; + } + request.result = undefined; + request.readyState = "done"; + const event2 = new FDBVersionChangeEvent("success", { + newVersion: null, + oldVersion + }); + request.dispatchEvent(event2); + }); + }); + return request; + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBFactory-open-IDBOpenDBRequest-DOMString-name-unsigned-long-long-version + open(name, version) { + validateRequiredArguments(arguments.length, 1, "IDBFactory.open"); + if (arguments.length > 1 && version !== undefined) { + // Based on spec, not sure why "MAX_SAFE_INTEGER" instead of "unsigned long long", but it's needed to pass + // tests + version = enforceRange(version, "MAX_SAFE_INTEGER"); + } + if (version === 0) { + throw new TypeError("Database version cannot be 0"); + } + const request = new FDBOpenDBRequest(); + request.source = null; + queueTask(() => { + openDatabase(this._databases, this._connectionQueues, name, version, request, (err, connection) => { + if (err) { + request.result = undefined; + request.readyState = "done"; + request.error = new DOMException(err.message, err.name); + const event = new FakeEvent("error", { + bubbles: true, + cancelable: true + }); + event.eventPath = []; + request.dispatchEvent(event); + return; + } + request.result = connection; + request.readyState = "done"; + const event2 = new FakeEvent("success"); + event2.eventPath = []; + request.dispatchEvent(event2); + }); + }); + return request; + } + + // https://w3c.github.io/IndexedDB/#dom-idbfactory-databases + databases() { + return Promise.resolve(Array.from(this._databases.entries(), ([name, database]) => { + const activeVersionChangeConnection = database.connections.find(connection => connection._runningVersionchangeTransaction); + // If a versionchange is in progress, report the old version. See `get-databases.any.js` test: + // "The result of databases() should contain the versions of databases at the time of calling, + // regardless of versionchange transactions currently running." + const version = activeVersionChangeConnection ? activeVersionChangeConnection._oldVersion : database.version; + return { + name, + version + }; + }).filter(({ + version + }) => { + // Ignore newly-created DBs with active versionchange transactions. See `get-databases.any.js` test: + // "The result of databases() should be only those databases which have been created at the + // time of calling, regardless of versionchange transactions currently running." + return version > 0; + })); + } + get [Symbol.toStringTag]() { + return "IDBFactory"; + } +} +export default FDBFactory; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/FDBIndex.js b/node_modules/fake-indexeddb/build/esm/FDBIndex.js new file mode 100644 index 0000000000000000000000000000000000000000..18e07a12be4012dbfeaa86ed11ada674da5382f2 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/FDBIndex.js @@ -0,0 +1,209 @@ +import FDBCursor from "./FDBCursor.js"; +import FDBCursorWithValue from "./FDBCursorWithValue.js"; +import FDBKeyRange from "./FDBKeyRange.js"; +import FDBRequest from "./FDBRequest.js"; +import { ConstraintError, InvalidStateError, TransactionInactiveError } from "./lib/errors.js"; +import FakeDOMStringList from "./lib/FakeDOMStringList.js"; +import valueToKey from "./lib/valueToKey.js"; +import valueToKeyRange from "./lib/valueToKeyRange.js"; +import { getKeyPath } from "./lib/getKeyPath.js"; +import extractGetAllOptions from "./lib/extractGetAllOptions.js"; +import enforceRange from "./lib/enforceRange.js"; +const confirmActiveTransaction = index => { + if (index._rawIndex.deleted || index.objectStore._rawObjectStore.deleted) { + throw new InvalidStateError(); + } + if (index.objectStore.transaction._state !== "active") { + throw new TransactionInactiveError(); + } +}; + +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#idl-def-IDBIndex +class FDBIndex { + constructor(objectStore, rawIndex) { + this._rawIndex = rawIndex; + this._name = rawIndex.name; + this.objectStore = objectStore; + this.keyPath = getKeyPath(rawIndex.keyPath); + this.multiEntry = rawIndex.multiEntry; + this.unique = rawIndex.unique; + } + get name() { + return this._name; + } + + // https://w3c.github.io/IndexedDB/#dom-idbindex-name + set name(name) { + const transaction = this.objectStore.transaction; + if (!transaction.db._runningVersionchangeTransaction) { + throw transaction._state === "active" ? new InvalidStateError() : new TransactionInactiveError(); + } + if (transaction._state !== "active") { + throw new TransactionInactiveError(); + } + if (this._rawIndex.deleted || this.objectStore._rawObjectStore.deleted) { + throw new InvalidStateError(); + } + name = String(name); + if (name === this._name) { + return; + } + if (this.objectStore.indexNames.contains(name)) { + throw new ConstraintError(); + } + const oldName = this._name; + const oldIndexNames = [...this.objectStore.indexNames]; + this._name = name; + this._rawIndex.name = name; + this.objectStore._indexesCache.delete(oldName); + this.objectStore._indexesCache.set(name, this); + this.objectStore._rawObjectStore.rawIndexes.delete(oldName); + this.objectStore._rawObjectStore.rawIndexes.set(name, this._rawIndex); + this.objectStore.indexNames = new FakeDOMStringList(...Array.from(this.objectStore._rawObjectStore.rawIndexes.keys()).filter(indexName => { + const index = this.objectStore._rawObjectStore.rawIndexes.get(indexName); + return index && !index.deleted; + }).sort()); + + // https://www.w3.org/TR/IndexedDB/#abort-an-upgrade-transaction - "If handle’s index was not newly created during transaction, set handle’s name to its index’s name." + if (!this.objectStore.transaction._createdIndexes.has(this._rawIndex)) { + transaction._rollbackLog.push(() => { + this._name = oldName; + this._rawIndex.name = oldName; + this.objectStore._indexesCache.delete(name); + this.objectStore._indexesCache.set(oldName, this); + this.objectStore._rawObjectStore.rawIndexes.delete(name); + this.objectStore._rawObjectStore.rawIndexes.set(oldName, this._rawIndex); + this.objectStore.indexNames = new FakeDOMStringList(...oldIndexNames); + }); + } + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-openCursor-IDBRequest-any-range-IDBCursorDirection-direction + openCursor(range, direction) { + confirmActiveTransaction(this); + if (range === null) { + range = undefined; + } + if (range !== undefined && !(range instanceof FDBKeyRange)) { + range = FDBKeyRange.only(valueToKey(range)); + } + const request = new FDBRequest(); + request.source = this; + request.transaction = this.objectStore.transaction; + const cursor = new FDBCursorWithValue(this, range, direction, request); + return this.objectStore.transaction._execRequestAsync({ + operation: cursor._iterate.bind(cursor), + request, + source: this + }); + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-openKeyCursor-IDBRequest-any-range-IDBCursorDirection-direction + openKeyCursor(range, direction) { + confirmActiveTransaction(this); + if (range === null) { + range = undefined; + } + if (range !== undefined && !(range instanceof FDBKeyRange)) { + range = FDBKeyRange.only(valueToKey(range)); + } + const request = new FDBRequest(); + request.source = this; + request.transaction = this.objectStore.transaction; + const cursor = new FDBCursor(this, range, direction, request, true); + return this.objectStore.transaction._execRequestAsync({ + operation: cursor._iterate.bind(cursor), + request, + source: this + }); + } + get(key) { + confirmActiveTransaction(this); + if (!(key instanceof FDBKeyRange)) { + key = valueToKey(key); + } + return this.objectStore.transaction._execRequestAsync({ + operation: this._rawIndex.getValue.bind(this._rawIndex, key), + source: this + }); + } + + // http://w3c.github.io/IndexedDB/#dom-idbindex-getall + getAll(queryOrOptions, count) { + const options = extractGetAllOptions(queryOrOptions, count, arguments.length); + confirmActiveTransaction(this); + const range = valueToKeyRange(options.query); + return this.objectStore.transaction._execRequestAsync({ + operation: this._rawIndex.getAllValues.bind(this._rawIndex, range, options.count, options.direction), + source: this + }); + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-getKey-IDBRequest-any-key + getKey(key) { + confirmActiveTransaction(this); + if (!(key instanceof FDBKeyRange)) { + key = valueToKey(key); + } + return this.objectStore.transaction._execRequestAsync({ + operation: this._rawIndex.getKey.bind(this._rawIndex, key), + source: this + }); + } + + // http://w3c.github.io/IndexedDB/#dom-idbindex-getallkeys + getAllKeys(queryOrOptions, count) { + const options = extractGetAllOptions(queryOrOptions, count, arguments.length); + confirmActiveTransaction(this); + const range = valueToKeyRange(options.query); + return this.objectStore.transaction._execRequestAsync({ + operation: this._rawIndex.getAllKeys.bind(this._rawIndex, range, options.count, options.direction), + source: this + }); + } + + // https://www.w3.org/TR/IndexedDB/#dom-idbobjectstore-getallrecords + getAllRecords(options) { + let query; + let count; + let direction; + if (options !== undefined) { + if (options.query !== undefined) { + query = options.query; + } + if (options.count !== undefined) { + count = enforceRange(options.count, "unsigned long"); + } + if (options.direction !== undefined) { + direction = options.direction; + } + } + confirmActiveTransaction(this); + const range = valueToKeyRange(query); + return this.objectStore.transaction._execRequestAsync({ + operation: this._rawIndex.getAllRecords.bind(this._rawIndex, range, count, direction), + source: this + }); + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-count-IDBRequest-any-key + count(key) { + confirmActiveTransaction(this); + if (key === null) { + key = undefined; + } + if (key !== undefined && !(key instanceof FDBKeyRange)) { + key = FDBKeyRange.only(valueToKey(key)); + } + return this.objectStore.transaction._execRequestAsync({ + operation: () => { + return this._rawIndex.count(key); + }, + source: this + }); + } + get [Symbol.toStringTag]() { + return "IDBIndex"; + } +} +export default FDBIndex; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/FDBKeyRange.js b/node_modules/fake-indexeddb/build/esm/FDBKeyRange.js new file mode 100644 index 0000000000000000000000000000000000000000..6d699c32799e6ec27957b095a844c26750555d32 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/FDBKeyRange.js @@ -0,0 +1,70 @@ +import cmp from "./lib/cmp.js"; +import { DataError } from "./lib/errors.js"; +import valueToKey from "./lib/valueToKey.js"; +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#range-concept +class FDBKeyRange { + static only(value) { + if (arguments.length === 0) { + throw new TypeError(); + } + value = valueToKey(value); + return new FDBKeyRange(value, value, false, false); + } + static lowerBound(lower, open = false) { + if (arguments.length === 0) { + throw new TypeError(); + } + lower = valueToKey(lower); + return new FDBKeyRange(lower, undefined, open, true); + } + static upperBound(upper, open = false) { + if (arguments.length === 0) { + throw new TypeError(); + } + upper = valueToKey(upper); + return new FDBKeyRange(undefined, upper, true, open); + } + static bound(lower, upper, lowerOpen = false, upperOpen = false) { + if (arguments.length < 2) { + throw new TypeError(); + } + const cmpResult = cmp(lower, upper); + if (cmpResult === 1 || cmpResult === 0 && (lowerOpen || upperOpen)) { + throw new DataError(); + } + lower = valueToKey(lower); + upper = valueToKey(upper); + return new FDBKeyRange(lower, upper, lowerOpen, upperOpen); + } + constructor(lower, upper, lowerOpen, upperOpen) { + this.lower = lower; + this.upper = upper; + this.lowerOpen = lowerOpen; + this.upperOpen = upperOpen; + } + + // https://w3c.github.io/IndexedDB/#dom-idbkeyrange-includes + includes(key) { + if (arguments.length === 0) { + throw new TypeError(); + } + key = valueToKey(key); + if (this.lower !== undefined) { + const cmpResult = cmp(this.lower, key); + if (cmpResult === 1 || cmpResult === 0 && this.lowerOpen) { + return false; + } + } + if (this.upper !== undefined) { + const cmpResult = cmp(this.upper, key); + if (cmpResult === -1 || cmpResult === 0 && this.upperOpen) { + return false; + } + } + return true; + } + get [Symbol.toStringTag]() { + return "IDBKeyRange"; + } +} +export default FDBKeyRange; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/FDBObjectStore.js b/node_modules/fake-indexeddb/build/esm/FDBObjectStore.js new file mode 100644 index 0000000000000000000000000000000000000000..6fb593f8c559e93cba4c3ef1a987fcb318f13210 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/FDBObjectStore.js @@ -0,0 +1,401 @@ +import FDBCursor from "./FDBCursor.js"; +import FDBCursorWithValue from "./FDBCursorWithValue.js"; +import FDBIndex from "./FDBIndex.js"; +import FDBKeyRange from "./FDBKeyRange.js"; +import FDBRequest from "./FDBRequest.js"; +import canInjectKey from "./lib/canInjectKey.js"; +import { ConstraintError, DataError, InvalidAccessError, InvalidStateError, NotFoundError, ReadOnlyError, TransactionInactiveError } from "./lib/errors.js"; +import extractKey from "./lib/extractKey.js"; +import FakeDOMStringList from "./lib/FakeDOMStringList.js"; +import Index from "./lib/Index.js"; +import validateKeyPath from "./lib/validateKeyPath.js"; +import valueToKey from "./lib/valueToKey.js"; +import valueToKeyRange from "./lib/valueToKeyRange.js"; +import { getKeyPath } from "./lib/getKeyPath.js"; +import extractGetAllOptions from "./lib/extractGetAllOptions.js"; +import enforceRange from "./lib/enforceRange.js"; +import { cloneValueForInsertion } from "./lib/cloneValueForInsertion.js"; +const confirmActiveTransaction = objectStore => { + if (objectStore._rawObjectStore.deleted) { + throw new InvalidStateError(); + } + if (objectStore.transaction._state !== "active") { + throw new TransactionInactiveError(); + } +}; +const buildRecordAddPut = (objectStore, value, key) => { + confirmActiveTransaction(objectStore); + if (objectStore.transaction.mode === "readonly") { + throw new ReadOnlyError(); + } + if (objectStore.keyPath !== null) { + if (key !== undefined) { + throw new DataError(); + } + } + const clone = cloneValueForInsertion(value, objectStore.transaction); + if (objectStore.keyPath !== null) { + const tempKey = extractKey(objectStore.keyPath, clone); + if (tempKey.type === "found") { + valueToKey(tempKey.key); + } else { + if (!objectStore._rawObjectStore.keyGenerator) { + throw new DataError(); + } else if (!canInjectKey(objectStore.keyPath, clone)) { + throw new DataError(); + } + } + } + if (objectStore.keyPath === null && objectStore._rawObjectStore.keyGenerator === null && key === undefined) { + throw new DataError(); + } + if (key !== undefined) { + key = valueToKey(key); + } + return { + key, + value: clone + }; +}; + +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#object-store +class FDBObjectStore { + _indexesCache = new Map(); + constructor(transaction, rawObjectStore) { + this._rawObjectStore = rawObjectStore; + this._name = rawObjectStore.name; + this.keyPath = getKeyPath(rawObjectStore.keyPath); + this.autoIncrement = rawObjectStore.autoIncrement; + this.transaction = transaction; + this.indexNames = new FakeDOMStringList(...Array.from(rawObjectStore.rawIndexes.keys()).sort()); + } + get name() { + return this._name; + } + + // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-name + set name(name) { + const transaction = this.transaction; + if (!transaction.db._runningVersionchangeTransaction) { + throw transaction._state === "active" ? new InvalidStateError() : new TransactionInactiveError(); + } + confirmActiveTransaction(this); + name = String(name); + if (name === this._name) { + return; + } + if (this._rawObjectStore.rawDatabase.rawObjectStores.has(name)) { + throw new ConstraintError(); + } + const oldName = this._name; + const oldObjectStoreNames = [...transaction.db.objectStoreNames]; + this._name = name; + this._rawObjectStore.name = name; + this.transaction._objectStoresCache.delete(oldName); + this.transaction._objectStoresCache.set(name, this); + this._rawObjectStore.rawDatabase.rawObjectStores.delete(oldName); + this._rawObjectStore.rawDatabase.rawObjectStores.set(name, this._rawObjectStore); + transaction.db.objectStoreNames = new FakeDOMStringList(...Array.from(this._rawObjectStore.rawDatabase.rawObjectStores.keys()).filter(objectStoreName => { + const objectStore = this._rawObjectStore.rawDatabase.rawObjectStores.get(objectStoreName); + return objectStore && !objectStore.deleted; + }).sort()); + const oldScope = new Set(transaction._scope); + const oldTransactionObjectStoreNames = [...transaction.objectStoreNames]; + this.transaction._scope.delete(oldName); + transaction._scope.add(name); + transaction.objectStoreNames = new FakeDOMStringList(...Array.from(transaction._scope).sort()); + + // https://www.w3.org/TR/IndexedDB/#abort-an-upgrade-transaction - "If handle’s object store was not newly created during transaction, set handle’s name to its object store’s name." + if (!this.transaction._createdObjectStores.has(this._rawObjectStore)) { + transaction._rollbackLog.push(() => { + this._name = oldName; + this._rawObjectStore.name = oldName; + this.transaction._objectStoresCache.delete(name); + this.transaction._objectStoresCache.set(oldName, this); + this._rawObjectStore.rawDatabase.rawObjectStores.delete(name); + this._rawObjectStore.rawDatabase.rawObjectStores.set(oldName, this._rawObjectStore); + transaction.db.objectStoreNames = new FakeDOMStringList(...oldObjectStoreNames); + transaction._scope = oldScope; + transaction.objectStoreNames = new FakeDOMStringList(...oldTransactionObjectStoreNames); + }); + } + } + put(value, key) { + if (arguments.length === 0) { + throw new TypeError(); + } + const record = buildRecordAddPut(this, value, key); + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.storeRecord.bind(this._rawObjectStore, record, false, this.transaction._rollbackLog), + source: this + }); + } + add(value, key) { + if (arguments.length === 0) { + throw new TypeError(); + } + const record = buildRecordAddPut(this, value, key); + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.storeRecord.bind(this._rawObjectStore, record, true, this.transaction._rollbackLog), + source: this + }); + } + delete(key) { + if (arguments.length === 0) { + throw new TypeError(); + } + confirmActiveTransaction(this); + if (this.transaction.mode === "readonly") { + throw new ReadOnlyError(); + } + if (!(key instanceof FDBKeyRange)) { + key = valueToKey(key); + } + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.deleteRecord.bind(this._rawObjectStore, key, this.transaction._rollbackLog), + source: this + }); + } + get(key) { + if (arguments.length === 0) { + throw new TypeError(); + } + confirmActiveTransaction(this); + if (!(key instanceof FDBKeyRange)) { + key = valueToKey(key); + } + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.getValue.bind(this._rawObjectStore, key), + source: this + }); + } + + // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-getall + getAll(queryOrOptions, count) { + const options = extractGetAllOptions(queryOrOptions, count, arguments.length); + confirmActiveTransaction(this); + const range = valueToKeyRange(options.query); + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.getAllValues.bind(this._rawObjectStore, range, options.count, options.direction), + source: this + }); + } + + // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-getkey + getKey(key) { + if (arguments.length === 0) { + throw new TypeError(); + } + confirmActiveTransaction(this); + if (!(key instanceof FDBKeyRange)) { + key = valueToKey(key); + } + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.getKey.bind(this._rawObjectStore, key), + source: this + }); + } + + // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-getallkeys + getAllKeys(queryOrOptions, count) { + const options = extractGetAllOptions(queryOrOptions, count, arguments.length); + confirmActiveTransaction(this); + const range = valueToKeyRange(options.query); + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.getAllKeys.bind(this._rawObjectStore, range, options.count, options.direction), + source: this + }); + } + + // https://www.w3.org/TR/IndexedDB/#dom-idbobjectstore-getallrecords + getAllRecords(options) { + let query; + let count; + let direction; + if (options !== undefined) { + if (options.query !== undefined) { + query = options.query; + } + if (options.count !== undefined) { + count = enforceRange(options.count, "unsigned long"); + } + if (options.direction !== undefined) { + direction = options.direction; + } + } + confirmActiveTransaction(this); + const range = valueToKeyRange(query); + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.getAllRecords.bind(this._rawObjectStore, range, count, direction), + source: this + }); + } + clear() { + confirmActiveTransaction(this); + if (this.transaction.mode === "readonly") { + throw new ReadOnlyError(); + } + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.clear.bind(this._rawObjectStore, this.transaction._rollbackLog), + source: this + }); + } + openCursor(range, direction) { + confirmActiveTransaction(this); + if (range === null) { + range = undefined; + } + if (range !== undefined && !(range instanceof FDBKeyRange)) { + range = FDBKeyRange.only(valueToKey(range)); + } + const request = new FDBRequest(); + request.source = this; + request.transaction = this.transaction; + const cursor = new FDBCursorWithValue(this, range, direction, request); + return this.transaction._execRequestAsync({ + operation: cursor._iterate.bind(cursor), + request, + source: this + }); + } + openKeyCursor(range, direction) { + confirmActiveTransaction(this); + if (range === null) { + range = undefined; + } + if (range !== undefined && !(range instanceof FDBKeyRange)) { + range = FDBKeyRange.only(valueToKey(range)); + } + const request = new FDBRequest(); + request.source = this; + request.transaction = this.transaction; + const cursor = new FDBCursor(this, range, direction, request, true); + return this.transaction._execRequestAsync({ + operation: cursor._iterate.bind(cursor), + request, + source: this + }); + } + + // tslint:-next-line max-line-length + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBObjectStore-createIndex-IDBIndex-DOMString-name-DOMString-sequence-DOMString--keyPath-IDBIndexParameters-optionalParameters + createIndex(name, keyPath, optionalParameters = {}) { + if (arguments.length < 2) { + throw new TypeError(); + } + const multiEntry = optionalParameters.multiEntry !== undefined ? optionalParameters.multiEntry : false; + const unique = optionalParameters.unique !== undefined ? optionalParameters.unique : false; + if (this.transaction.mode !== "versionchange") { + throw new InvalidStateError(); + } + confirmActiveTransaction(this); + if (this.indexNames.contains(name)) { + throw new ConstraintError(); + } + validateKeyPath(keyPath); + if (Array.isArray(keyPath) && multiEntry) { + throw new InvalidAccessError(); + } + + // The index that is requested to be created can contain constraints on the data allowed in the index's + // referenced object store, such as requiring uniqueness of the values referenced by the index's keyPath. If the + // referenced object store already contains data which violates these constraints, this MUST NOT cause the + // implementation of createIndex to throw an exception or affect what it returns. The implementation MUST still + // create and return an IDBIndex object. Instead the implementation must queue up an operation to abort the + // "versionchange" transaction which was used for the createIndex call. + + // Save for rollbackLog + const indexNames = [...this.indexNames]; + const index = new Index(this._rawObjectStore, name, keyPath, multiEntry, unique); + this.indexNames._push(name); + this.indexNames._sort(); + this.transaction._createdIndexes.add(index); + this._rawObjectStore.rawIndexes.set(name, index); + index.initialize(this.transaction); // This is async by design + + this.transaction._rollbackLog.push(() => { + index.deleted = true; + this.indexNames = new FakeDOMStringList(...indexNames); + this._rawObjectStore.rawIndexes.delete(index.name); + }); + return new FDBIndex(this, index); + } + + // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-index + index(name) { + if (arguments.length === 0) { + throw new TypeError(); + } + if (this._rawObjectStore.deleted || this.transaction._state === "finished") { + throw new InvalidStateError(); + } + const index = this._indexesCache.get(name); + if (index !== undefined) { + return index; + } + const rawIndex = this._rawObjectStore.rawIndexes.get(name); + if (!this.indexNames.contains(name) || rawIndex === undefined) { + throw new NotFoundError(); + } + const index2 = new FDBIndex(this, rawIndex); + this._indexesCache.set(name, index2); + return index2; + } + deleteIndex(name) { + if (arguments.length === 0) { + throw new TypeError(); + } + if (this.transaction.mode !== "versionchange") { + throw new InvalidStateError(); + } + confirmActiveTransaction(this); + const rawIndex = this._rawObjectStore.rawIndexes.get(name); + if (rawIndex === undefined) { + throw new NotFoundError(); + } + this.transaction._rollbackLog.push(() => { + rawIndex.deleted = false; + this._rawObjectStore.rawIndexes.set(rawIndex.name, rawIndex); + this.indexNames._push(rawIndex.name); + this.indexNames._sort(); + }); + this.indexNames = new FakeDOMStringList(...Array.from(this.indexNames).filter(indexName => { + return indexName !== name; + })); + rawIndex.deleted = true; // Not sure if this is supposed to happen synchronously + + this.transaction._execRequestAsync({ + operation: () => { + const rawIndex2 = this._rawObjectStore.rawIndexes.get(name); + + // Hack in case another index is given this name before this async request is processed. It'd be better + // to have a real unique ID for each index. + if (rawIndex === rawIndex2) { + this._rawObjectStore.rawIndexes.delete(name); + } + }, + source: this + }); + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBObjectStore-count-IDBRequest-any-key + count(key) { + confirmActiveTransaction(this); + if (key === null) { + key = undefined; + } + if (key !== undefined && !(key instanceof FDBKeyRange)) { + key = FDBKeyRange.only(valueToKey(key)); + } + return this.transaction._execRequestAsync({ + operation: () => { + return this._rawObjectStore.count(key); + }, + source: this + }); + } + get [Symbol.toStringTag]() { + return "IDBObjectStore"; + } +} +export default FDBObjectStore; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/FDBOpenDBRequest.js b/node_modules/fake-indexeddb/build/esm/FDBOpenDBRequest.js new file mode 100644 index 0000000000000000000000000000000000000000..1615a54d7b97f0ffc4dcf8ccd501095427e85a80 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/FDBOpenDBRequest.js @@ -0,0 +1,9 @@ +import FDBRequest from "./FDBRequest.js"; +class FDBOpenDBRequest extends FDBRequest { + onupgradeneeded = null; + onblocked = null; + get [Symbol.toStringTag]() { + return "IDBOpenDBRequest"; + } +} +export default FDBOpenDBRequest; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/FDBRecord.js b/node_modules/fake-indexeddb/build/esm/FDBRecord.js new file mode 100644 index 0000000000000000000000000000000000000000..b493df2d1b74ac7199a24da6455816a685d19d68 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/FDBRecord.js @@ -0,0 +1,29 @@ +class FDBRecord { + constructor(key, primaryKey, value) { + this._key = key; + this._primaryKey = primaryKey; + this._value = value; + } + get key() { + return this._key; + } + set key(_) { + /* for babel */ + } + get primaryKey() { + return this._primaryKey; + } + set primaryKey(_) { + /* for babel */ + } + get value() { + return this._value; + } + set value(_) { + /* for babel */ + } + get [Symbol.toStringTag]() { + return "IDBRecord"; + } +} +export default FDBRecord; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/FDBRequest.js b/node_modules/fake-indexeddb/build/esm/FDBRequest.js new file mode 100644 index 0000000000000000000000000000000000000000..bae3a62302b5f6f5b6235db6e2d9b104d7e7483a --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/FDBRequest.js @@ -0,0 +1,33 @@ +import { InvalidStateError } from "./lib/errors.js"; +import FakeEventTarget from "./lib/FakeEventTarget.js"; +class FDBRequest extends FakeEventTarget { + _result = null; + _error = null; + source = null; + transaction = null; + readyState = "pending"; + onsuccess = null; + onerror = null; + get error() { + if (this.readyState === "pending") { + throw new InvalidStateError(); + } + return this._error; + } + set error(value) { + this._error = value; + } + get result() { + if (this.readyState === "pending") { + throw new InvalidStateError(); + } + return this._result; + } + set result(value) { + this._result = value; + } + get [Symbol.toStringTag]() { + return "IDBRequest"; + } +} +export default FDBRequest; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/FDBTransaction.js b/node_modules/fake-indexeddb/build/esm/FDBTransaction.js new file mode 100644 index 0000000000000000000000000000000000000000..9c5654e963ceee0e96c3a5183598c2c3f2fafd09 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/FDBTransaction.js @@ -0,0 +1,264 @@ +import FDBObjectStore from "./FDBObjectStore.js"; +import FDBRequest from "./FDBRequest.js"; +import { AbortError, InvalidStateError, NotFoundError, TransactionInactiveError } from "./lib/errors.js"; +import FakeDOMStringList from "./lib/FakeDOMStringList.js"; +import FakeEvent from "./lib/FakeEvent.js"; +import FakeEventTarget from "./lib/FakeEventTarget.js"; +import { queueTask } from "./lib/scheduling.js"; +const prioritizedListenerTypes = ["error", "abort", "complete"]; +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#transaction +class FDBTransaction extends FakeEventTarget { + _state = "active"; + _started = false; + _rollbackLog = []; + _objectStoresCache = new Map(); + _openRequest = null; + error = null; + onabort = null; + oncomplete = null; + onerror = null; + _prioritizedListeners = new Map(); + _requests = []; + _createdIndexes = new Set(); + _createdObjectStores = new Set(); + constructor(storeNames, mode, durability, db) { + super(); + this._scope = new Set(storeNames); + this.mode = mode; + this.durability = durability; + this.db = db; + this.objectStoreNames = new FakeDOMStringList(...Array.from(this._scope).sort()); + for (const type of prioritizedListenerTypes) { + // Attach prioritized (internal) listeners before any external listeners are attached. + // This ensures that these listeners run with the same timing regardless of whether + // the user uses `on*` or `addEventListener` for event listeners. + this.addEventListener(type, () => { + this._prioritizedListeners.get(type)?.(); + }); + } + } + + // https://w3c.github.io/IndexedDB/#abort-transaction + _abort(errName) { + for (const f of this._rollbackLog.reverse()) { + f(); + } + if (errName !== null) { + const e = new DOMException(undefined, errName); + this.error = e; + } + + // Should this directly remove from _requests? + for (const { + request + } of this._requests) { + if (request.readyState !== "done") { + request.readyState = "done"; // This will cancel execution of this request's operation + if (request.source) { + // https://w3c.github.io/IndexedDB/#ref-for-list-iterate%E2%91%A2 + // For each request of transaction’s request list, abort the steps to asynchronously + // execute a request for request, set request’s processed flag to true, and queue a + // database task to run these steps: + queueTask(() => { + // Set request’s result to undefined. + request.result = undefined; + // Set request’s error to a newly created "AbortError" DOMException. + request.error = new AbortError(); + + // Fire an event named error at request with its bubbles and cancelable attributes initialized + // to true. + const event = new FakeEvent("error", { + bubbles: true, + cancelable: true + }); + event.eventPath = [this.db, this]; + try { + request.dispatchEvent(event); + } catch (_err) { + if (this._state === "active") { + this._abort("AbortError"); + } + } + }); + } + } + } + + // Queue a database task to run these steps: + queueTask(() => { + // If transaction is an upgrade transaction, then set transaction’s connection’s associated database’s + // upgrade transaction to null. + // (i.e. remove it from the list of `db.connections`) + const isUpgradeTransaction = this.mode === "versionchange"; + if (isUpgradeTransaction) { + this.db._rawDatabase.connections = this.db._rawDatabase.connections.filter(connection => !connection._rawDatabase.transactions.includes(this)); + } + // Fire an event named abort at transaction with its bubbles attribute initialized to true. + const event = new FakeEvent("abort", { + bubbles: true, + cancelable: false + }); + event.eventPath = [this.db]; + this.dispatchEvent(event); + + // If transaction is an upgrade transaction, then: + if (isUpgradeTransaction) { + // Let request be the open request associated with transaction. + const request = this._openRequest; + // Set request’s transaction to null. + request.transaction = null; + // Set request’s result to undefined. + request.result = undefined; + } + }); + this._state = "finished"; + } + abort() { + if (this._state === "committing" || this._state === "finished") { + throw new InvalidStateError(); + } + this._state = "active"; + this._abort(null); + } + + // http://w3c.github.io/IndexedDB/#dom-idbtransaction-objectstore + objectStore(name) { + if (this._state !== "active") { + throw new InvalidStateError(); + } + const objectStore = this._objectStoresCache.get(name); + if (objectStore !== undefined) { + return objectStore; + } + const rawObjectStore = this.db._rawDatabase.rawObjectStores.get(name); + if (!this._scope.has(name) || rawObjectStore === undefined) { + throw new NotFoundError(); + } + const objectStore2 = new FDBObjectStore(this, rawObjectStore); + this._objectStoresCache.set(name, objectStore2); + return objectStore2; + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-asynchronously-executing-a-request + _execRequestAsync(obj) { + const source = obj.source; + const operation = obj.operation; + let request = Object.hasOwn(obj, "request") ? obj.request : null; + if (this._state !== "active") { + throw new TransactionInactiveError(); + } + + // Request should only be passed for cursors + if (!request) { + if (!source) { + // Special requests like indexes that just need to run some code + request = new FDBRequest(); + } else { + request = new FDBRequest(); + request.source = source; + request.transaction = source.transaction; + } + } + this._requests.push({ + operation, + request + }); + return request; + } + _start() { + this._started = true; + + // Remove from request queue - cursor ones will be added back if necessary by cursor.continue and such + let operation; + let request; + while (this._requests.length > 0) { + const r = this._requests.shift(); + + // This should only be false if transaction was aborted + if (r && r.request.readyState !== "done") { + request = r.request; + operation = r.operation; + break; + } + } + if (request && operation) { + if (!request.source) { + // Special requests like indexes that just need to run some code, with error handling already built into + // operation + operation(); + } else { + let defaultAction; + let event; + try { + const result = operation(); + request.readyState = "done"; + request.result = result; + request.error = undefined; + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-fire-a-success-event + if (this._state === "inactive") { + this._state = "active"; + } + event = new FakeEvent("success", { + bubbles: false, + cancelable: false + }); + } catch (err) { + request.readyState = "done"; + request.result = undefined; + request.error = err; + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-fire-an-error-event + if (this._state === "inactive") { + this._state = "active"; + } + event = new FakeEvent("error", { + bubbles: true, + cancelable: true + }); + defaultAction = this._abort.bind(this, err.name); + } + try { + event.eventPath = [this.db, this]; + request.dispatchEvent(event); + } catch (_err) { + if (this._state === "active") { + this._abort("AbortError"); + defaultAction = undefined; // do not abort again + } + } + + // Default action of event + if (!event.canceled) { + if (defaultAction) { + defaultAction(); + } + } + } + + // Give it another chance for new handlers to be set before finishing + queueTask(this._start.bind(this)); + return; + } + + // Check if transaction complete event needs to be fired + if (this._state !== "finished") { + // Either aborted or committed already + this._state = "finished"; + if (!this.error) { + const event = new FakeEvent("complete"); + this.dispatchEvent(event); + } + } + } + commit() { + if (this._state !== "active") { + throw new InvalidStateError(); + } + this._state = "committing"; + } + get [Symbol.toStringTag]() { + return "IDBTransaction"; + } +} +export default FDBTransaction; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/FDBVersionChangeEvent.js b/node_modules/fake-indexeddb/build/esm/FDBVersionChangeEvent.js new file mode 100644 index 0000000000000000000000000000000000000000..2a1bc77a3338b51afdf3f966832fb18d62bce44e --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/FDBVersionChangeEvent.js @@ -0,0 +1,12 @@ +import FakeEvent from "./lib/FakeEvent.js"; +class FDBVersionChangeEvent extends FakeEvent { + constructor(type, parameters = {}) { + super(type); + this.newVersion = parameters.newVersion !== undefined ? parameters.newVersion : null; + this.oldVersion = parameters.oldVersion !== undefined ? parameters.oldVersion : 0; + } + get [Symbol.toStringTag]() { + return "IDBVersionChangeEvent"; + } +} +export default FDBVersionChangeEvent; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/fakeIndexedDB.js b/node_modules/fake-indexeddb/build/esm/fakeIndexedDB.js new file mode 100644 index 0000000000000000000000000000000000000000..c86f470ab1a3296ce10262813ec9cfd2b4cbfb8e --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/fakeIndexedDB.js @@ -0,0 +1,3 @@ +import FDBFactory from "./FDBFactory.js"; +const fakeIndexedDB = new FDBFactory(); +export default fakeIndexedDB; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/forceCloseDatabase.js b/node_modules/fake-indexeddb/build/esm/forceCloseDatabase.js new file mode 100644 index 0000000000000000000000000000000000000000..69714e474b2ac110938fa5616b1c039057610817 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/forceCloseDatabase.js @@ -0,0 +1,21 @@ +import closeConnection from "./lib/closeConnection.js"; +/** + * Forcibly closes a database. This simulates a database being closed due to abnormal reasons, such as + * using DevTools to clear data while a database is open. Spec-wise, this is equivalent to + * [closing a database connection](https://www.w3.org/TR/IndexedDB/#closing-connection) with the `forced flag` + * set to true. + * + * Use this API if you want to have more test coverage for unusual IndexedDB events, such as a database firing + * the "close" event: + * + * ```js + * db.addEventListener("close", () => { + * console.log("Forcibly closed!"); + * }); + * forceCloseDatabase(db); // invokes the event listener + * ``` + * @param db + */ +export default function forceCloseDatabase(db) { + closeConnection(db, true); +} \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/index.js b/node_modules/fake-indexeddb/build/esm/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b0a051bba02c72d1443b13897eeba4a8cfe6cce4 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/index.js @@ -0,0 +1,16 @@ +import fakeIndexedDB from "./fakeIndexedDB.js"; +export default fakeIndexedDB; +export { fakeIndexedDB as indexedDB }; +export { default as IDBCursor } from "./FDBCursor.js"; +export { default as IDBCursorWithValue } from "./FDBCursorWithValue.js"; +export { default as IDBDatabase } from "./FDBDatabase.js"; +export { default as IDBFactory } from "./FDBFactory.js"; +export { default as IDBIndex } from "./FDBIndex.js"; +export { default as IDBKeyRange } from "./FDBKeyRange.js"; +export { default as IDBObjectStore } from "./FDBObjectStore.js"; +export { default as IDBOpenDBRequest } from "./FDBOpenDBRequest.js"; +export { default as IDBRecord } from "./FDBRecord.js"; +export { default as IDBRequest } from "./FDBRequest.js"; +export { default as IDBTransaction } from "./FDBTransaction.js"; +export { default as IDBVersionChangeEvent } from "./FDBVersionChangeEvent.js"; +export { default as forceCloseDatabase } from "./forceCloseDatabase.js"; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/Database.js b/node_modules/fake-indexeddb/build/esm/lib/Database.js new file mode 100644 index 0000000000000000000000000000000000000000..fb9c97e0326b7efb4bbff3dee5c2d484dae7745c --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/Database.js @@ -0,0 +1,44 @@ +import { queueTask } from "./scheduling.js"; +import { intersection } from "./intersection.js"; +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-database +class Database { + transactions = []; + rawObjectStores = new Map(); + connections = []; + constructor(name, version) { + this.name = name; + this.version = version; + this.processTransactions = this.processTransactions.bind(this); + } + processTransactions() { + queueTask(() => { + const running = this.transactions.filter(transaction => transaction._started && transaction._state !== "finished"); + const waiting = this.transactions.filter(transaction => !transaction._started && transaction._state !== "finished"); + + // The next transaction to run is the first waiting one that doesn't overlap with either a running one or a + // preceding waiting one. This allows non-overlapping transactions to run in parallel. + // The exception is readonly transactions, which are allowed to run in parallel with other readonly + // transactions, even with overlapping scopes, since no data is being modified. + const next = waiting.find((transaction, i) => { + const anyRunning = running.some(other => !(transaction.mode === "readonly" && other.mode === "readonly") && intersection(other._scope, transaction._scope).size > 0); + if (anyRunning) { + return false; + } + + // If any _preceding_ waiting transactions are blocked, then that's also blocking. + // E.g. if you have 3 transactions: [a], [a,b], and [b,c], then [a] blocks [a,b] which blocks [b,c] + // until [a] is complete, even though [a] and [b,c] share no overlap. + // Note that readonly transactions do not have to be handled as a special case here, + // because if any transactions with overlapping scopes are blocked, then we can assume they are + const anyWaiting = waiting.slice(0, i).some(other => intersection(other._scope, transaction._scope).size > 0); + return !anyWaiting; + }); + if (next) { + next.addEventListener("complete", this.processTransactions); + next.addEventListener("abort", this.processTransactions); + next._start(); + } + }); + } +} +export default Database; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/FakeDOMStringList.js b/node_modules/fake-indexeddb/build/esm/lib/FakeDOMStringList.js new file mode 100644 index 0000000000000000000000000000000000000000..38447e01f11b22a1687ca0cf2a862d7feb33451d --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/FakeDOMStringList.js @@ -0,0 +1,41 @@ +class FakeDOMStringList { + constructor(...values) { + this._values = values; + for (let i = 0; i < values.length; i++) { + this[i] = values[i]; + } + } + contains(value) { + return this._values.includes(value); + } + item(i) { + if (i < 0 || i >= this._values.length) { + return null; + } + return this._values[i]; + } + get length() { + return this._values.length; + } + [Symbol.iterator]() { + return this._values[Symbol.iterator](); + } + + // Handled by proxy + + // Used internally, should not be used by others. I could maybe get rid of these and replace rather than mutate, but too lazy to check the spec. + _push(...values) { + for (let i = 0; i < values.length; i++) { + this[this._values.length + i] = values[i]; + } + this._values.push(...values); + } + _sort(...values) { + this._values.sort(...values); + for (let i = 0; i < this._values.length; i++) { + this[i] = this._values[i]; + } + return this; + } +} +export default FakeDOMStringList; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/FakeEvent.js b/node_modules/fake-indexeddb/build/esm/lib/FakeEvent.js new file mode 100644 index 0000000000000000000000000000000000000000..15a20b2e5ce42e3192209a2f6f4db6375dca2766 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/FakeEvent.js @@ -0,0 +1,38 @@ +class Event { + eventPath = []; + NONE = 0; + CAPTURING_PHASE = 1; + AT_TARGET = 2; + BUBBLING_PHASE = 3; + + // Flags + propagationStopped = false; + immediatePropagationStopped = false; + canceled = false; + initialized = true; + dispatched = false; + target = null; + currentTarget = null; + eventPhase = 0; + defaultPrevented = false; + isTrusted = false; + timeStamp = Date.now(); + constructor(type, eventInitDict = {}) { + this.type = type; + this.bubbles = eventInitDict.bubbles !== undefined ? eventInitDict.bubbles : false; + this.cancelable = eventInitDict.cancelable !== undefined ? eventInitDict.cancelable : false; + } + preventDefault() { + if (this.cancelable) { + this.canceled = true; + } + } + stopPropagation() { + this.propagationStopped = true; + } + stopImmediatePropagation() { + this.propagationStopped = true; + this.immediatePropagationStopped = true; + } +} +export default Event; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/FakeEventTarget.js b/node_modules/fake-indexeddb/build/esm/lib/FakeEventTarget.js new file mode 100644 index 0000000000000000000000000000000000000000..ce2fb437be77cc87b231beb0225845562a9dc461 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/FakeEventTarget.js @@ -0,0 +1,120 @@ +import { InvalidStateError } from "./errors.js"; +const stopped = (event, listener) => { + return event.immediatePropagationStopped || event.eventPhase === event.CAPTURING_PHASE && listener.capture === false || event.eventPhase === event.BUBBLING_PHASE && listener.capture === true; +}; + +// http://www.w3.org/TR/dom/#concept-event-listener-invoke +const invokeEventListeners = (event, obj) => { + event.currentTarget = obj; + const errors = []; + const invoke = callbackOrObject => { + try { + const callback = typeof callbackOrObject === "function" ? callbackOrObject : callbackOrObject.handleEvent; + // @ts-expect-error EventCallback's types are not quite right here + callback.call(event.currentTarget, event); + } catch (err) { + errors.push(err); + } + }; + + // The callback might cause obj.listeners to mutate as we traverse it. + // Take a copy of the array so that nothing sneaks in and we don't lose + // our place. + for (const listener of obj.listeners.slice()) { + if (event.type !== listener.type || stopped(event, listener)) { + continue; + } + invoke(listener.callback); + } + const typeToProp = { + abort: "onabort", + blocked: "onblocked", + close: "onclose", + complete: "oncomplete", + error: "onerror", + success: "onsuccess", + upgradeneeded: "onupgradeneeded", + versionchange: "onversionchange" + }; + const prop = typeToProp[event.type]; + if (prop === undefined) { + throw new Error(`Unknown event type: "${event.type}"`); + } + const callback = event.currentTarget[prop]; + if (callback) { + const listener = { + callback, + capture: false, + type: event.type + }; + if (!stopped(event, listener)) { + invoke(listener.callback); + } + } + + // we want to execute all listeners before deciding if we want to throw, because there could be an error thrown by + // the first listener, but the second should still be invoked + if (errors.length) { + throw new AggregateError(errors); + } +}; +class FakeEventTarget { + listeners = []; + + // These will be overridden in individual subclasses and made not readonly + + addEventListener(type, callback, options) { + const capture = !!(typeof options === "object" && options ? options.capture : options); + this.listeners.push({ + callback, + capture, + type + }); + } + removeEventListener(type, callback, options) { + const capture = !!(typeof options === "object" && options ? options.capture : options); + const i = this.listeners.findIndex(listener => { + return listener.type === type && listener.callback === callback && listener.capture === capture; + }); + this.listeners.splice(i, 1); + } + + // http://www.w3.org/TR/dom/#dispatching-events + dispatchEvent(event) { + if (event.dispatched || !event.initialized) { + throw new InvalidStateError("The object is in an invalid state."); + } + event.isTrusted = false; + event.dispatched = true; + event.target = this; + // NOT SURE WHEN THIS SHOULD BE SET event.eventPath = []; + + event.eventPhase = event.CAPTURING_PHASE; + for (const obj of event.eventPath) { + if (!event.propagationStopped) { + invokeEventListeners(event, obj); + } + } + event.eventPhase = event.AT_TARGET; + if (!event.propagationStopped) { + invokeEventListeners(event, event.target); + } + if (event.bubbles) { + event.eventPath.reverse(); + event.eventPhase = event.BUBBLING_PHASE; + for (const obj of event.eventPath) { + if (!event.propagationStopped) { + invokeEventListeners(event, obj); + } + } + } + event.dispatched = false; + event.eventPhase = event.NONE; + event.currentTarget = null; + if (event.canceled) { + return false; + } + return true; + } +} +export default FakeEventTarget; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/Index.js b/node_modules/fake-indexeddb/build/esm/lib/Index.js new file mode 100644 index 0000000000000000000000000000000000000000..de0b14be5b1fee07ba204d271da0458daea609a0 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/Index.js @@ -0,0 +1,172 @@ +import FDBRecord from "../FDBRecord.js"; +import { ConstraintError } from "./errors.js"; +import extractKey from "./extractKey.js"; +import RecordStore from "./RecordStore.js"; +import valueToKey from "./valueToKey.js"; +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-index +class Index { + deleted = false; + // Initialized should be used to decide whether to throw an error or abort the versionchange transaction when there is a + // constraint + initialized = false; + constructor(rawObjectStore, name, keyPath, multiEntry, unique) { + this.rawObjectStore = rawObjectStore; + this.name = name; + this.keyPath = keyPath; + this.multiEntry = multiEntry; + this.unique = unique; + this.records = new RecordStore(unique); + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-retrieving-a-value-from-an-index + getKey(key) { + const record = this.records.get(key); + return record !== undefined ? record.value : undefined; + } + + // http://w3c.github.io/IndexedDB/#retrieve-multiple-referenced-values-from-an-index + getAllKeys(range, count, direction) { + if (count === undefined || count === 0) { + count = Infinity; + } + const records = []; + for (const record of this.records.values(range, direction)) { + records.push(structuredClone(record.value)); + if (records.length >= count) { + break; + } + } + return records; + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#index-referenced-value-retrieval-operation + getValue(key) { + const record = this.records.get(key); + return record !== undefined ? this.rawObjectStore.getValue(record.value) : undefined; + } + + // http://w3c.github.io/IndexedDB/#retrieve-multiple-referenced-values-from-an-index + getAllValues(range, count, direction) { + if (count === undefined || count === 0) { + count = Infinity; + } + const records = []; + for (const record of this.records.values(range, direction)) { + records.push(this.rawObjectStore.getValue(record.value)); + if (records.length >= count) { + break; + } + } + return records; + } + + // https://www.w3.org/TR/IndexedDB/#dom-idbindex-getallrecords + getAllRecords(range, count, direction) { + if (count === undefined || count === 0) { + count = Infinity; + } + const records = []; + for (const record of this.records.values(range, direction)) { + records.push(new FDBRecord(structuredClone(record.key), structuredClone(this.rawObjectStore.getKey(record.value)), this.rawObjectStore.getValue(record.value))); + if (records.length >= count) { + break; + } + } + return records; + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-storing-a-record-into-an-object-store (step 7) + storeRecord(newRecord) { + let indexKey; + try { + indexKey = extractKey(this.keyPath, newRecord.value).key; + } catch (err) { + if (err.name === "DataError") { + // Invalid key is not an actual error, just means we do not store an entry in this index + return; + } + throw err; + } + if (!this.multiEntry || !Array.isArray(indexKey)) { + try { + valueToKey(indexKey); + } catch (e) { + return; + } + } else { + // remove any elements from index key that are not valid keys and remove any duplicate elements from index + // key such that only one instance of the duplicate value remains. + const keep = []; + for (const part of indexKey) { + if (keep.indexOf(part) < 0) { + try { + keep.push(valueToKey(part)); + } catch (err) { + /* Do nothing */ + } + } + } + indexKey = keep; + } + if (!this.multiEntry || !Array.isArray(indexKey)) { + if (this.unique) { + const existingRecord = this.records.get(indexKey); + if (existingRecord) { + throw new ConstraintError(); + } + } + } else { + if (this.unique) { + for (const individualIndexKey of indexKey) { + const existingRecord = this.records.get(individualIndexKey); + if (existingRecord) { + throw new ConstraintError(); + } + } + } + } + if (!this.multiEntry || !Array.isArray(indexKey)) { + this.records.put({ + key: indexKey, + value: newRecord.key + }); + } else { + for (const individualIndexKey of indexKey) { + this.records.put({ + key: individualIndexKey, + value: newRecord.key + }); + } + } + } + initialize(transaction) { + if (this.initialized) { + throw new Error("Index already initialized"); + } + transaction._execRequestAsync({ + operation: () => { + try { + // Create index based on current value of objectstore + for (const record of this.rawObjectStore.records.values()) { + this.storeRecord(record); + } + this.initialized = true; + } catch (err) { + // console.error(err); + transaction._abort(err.name); + } + }, + source: null + }); + } + count(range) { + let count = 0; + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + for (const record of this.records.values(range)) { + count += 1; + } + return count; + } +} +export default Index; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/KeyGenerator.js b/node_modules/fake-indexeddb/build/esm/lib/KeyGenerator.js new file mode 100644 index 0000000000000000000000000000000000000000..5f5976cddfbd0c4d71888c755f31d4cd6e908be4 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/KeyGenerator.js @@ -0,0 +1,22 @@ +import { ConstraintError } from "./errors.js"; +const MAX_KEY = 9007199254740992; +class KeyGenerator { + // This is kind of wrong. Should start at 1 and increment only after record is saved + num = 0; + next() { + if (this.num >= MAX_KEY) { + throw new ConstraintError(); + } + this.num += 1; + return this.num; + } + + // https://w3c.github.io/IndexedDB/#possibly-update-the-key-generator + setIfLarger(num) { + const value = Math.floor(Math.min(num, MAX_KEY)) - 1; + if (value >= this.num) { + this.num = value + 1; + } + } +} +export default KeyGenerator; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/ObjectStore.js b/node_modules/fake-indexeddb/build/esm/lib/ObjectStore.js new file mode 100644 index 0000000000000000000000000000000000000000..8dafa6c65aabddbc55ba1371189989c709c33930 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/ObjectStore.js @@ -0,0 +1,238 @@ +import FDBRecord from "../FDBRecord.js"; +import { DataError } from "./errors.js"; +import extractKey from "./extractKey.js"; +import KeyGenerator from "./KeyGenerator.js"; +import RecordStore from "./RecordStore.js"; +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-object-store +class ObjectStore { + deleted = false; + records = new RecordStore(true); + rawIndexes = new Map(); + constructor(rawDatabase, name, keyPath, autoIncrement) { + this.rawDatabase = rawDatabase; + this.keyGenerator = autoIncrement === true ? new KeyGenerator() : null; + this.deleted = false; + this.name = name; + this.keyPath = keyPath; + this.autoIncrement = autoIncrement; + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-retrieving-a-value-from-an-object-store + getKey(key) { + const record = this.records.get(key); + return record !== undefined ? structuredClone(record.key) : undefined; + } + + // http://w3c.github.io/IndexedDB/#retrieve-multiple-keys-from-an-object-store + getAllKeys(range, count, direction) { + if (count === undefined || count === 0) { + count = Infinity; + } + const records = []; + for (const record of this.records.values(range, direction)) { + records.push(structuredClone(record.key)); + if (records.length >= count) { + break; + } + } + return records; + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-retrieving-a-value-from-an-object-store + getValue(key) { + const record = this.records.get(key); + return record !== undefined ? structuredClone(record.value) : undefined; + } + + // http://w3c.github.io/IndexedDB/#retrieve-multiple-values-from-an-object-store + getAllValues(range, count, direction) { + if (count === undefined || count === 0) { + count = Infinity; + } + const records = []; + for (const record of this.records.values(range, direction)) { + records.push(structuredClone(record.value)); + if (records.length >= count) { + break; + } + } + return records; + } + + // https://www.w3.org/TR/IndexedDB/#dom-idbobjectstore-getallrecords + getAllRecords(range, count, direction) { + if (count === undefined || count === 0) { + count = Infinity; + } + const records = []; + for (const record of this.records.values(range, direction)) { + records.push(new FDBRecord(structuredClone(record.key), structuredClone(record.key), structuredClone(record.value))); + if (records.length >= count) { + break; + } + } + return records; + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-storing-a-record-into-an-object-store + storeRecord(newRecord, noOverwrite, rollbackLog) { + if (this.keyPath !== null) { + const key = extractKey(this.keyPath, newRecord.value).key; + if (key !== undefined) { + newRecord.key = key; + } + } + const rollbackLogForThisOperation = []; + if (this.keyGenerator !== null && newRecord.key === undefined) { + let rolledBack = false; + const keyGeneratorBefore = this.keyGenerator.num; + const rollbackKeyGenerator = () => { + if (rolledBack) { + return; + } + rolledBack = true; + if (this.keyGenerator) { + this.keyGenerator.num = keyGeneratorBefore; + } + }; + rollbackLogForThisOperation.push(rollbackKeyGenerator); + if (rollbackLog) { + rollbackLog.push(rollbackKeyGenerator); + } + newRecord.key = this.keyGenerator.next(); + + // Set in value if keyPath defiend but led to no key + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-to-assign-a-key-to-a-value-using-a-key-path + if (this.keyPath !== null) { + if (Array.isArray(this.keyPath)) { + throw new Error("Cannot have an array key path in an object store with a key generator"); + } + let remainingKeyPath = this.keyPath; + let object = newRecord.value; + let identifier; + let i = 0; // Just to run the loop at least once + while (i >= 0) { + if (typeof object !== "object") { + throw new DataError(); + } + i = remainingKeyPath.indexOf("."); + if (i >= 0) { + identifier = remainingKeyPath.slice(0, i); + remainingKeyPath = remainingKeyPath.slice(i + 1); + if (!Object.hasOwn(object, identifier)) { + // Bypass prototype when setting (See `bindings-inject-values-bypass.any.js`) + // Equivalent to `object[identifier] = ...` without using `Object.prototype` + Object.defineProperty(object, identifier, { + configurable: true, + enumerable: true, + writable: true, + value: {} + }); + } + object = object[identifier]; + } + } + identifier = remainingKeyPath; + + // Bypass prototype when setting (See `bindings-inject-values-bypass.any.js`) + // Equivalent to `object[identifier] = ...` without using `Object.prototype` + Object.defineProperty(object, identifier, { + configurable: true, + enumerable: true, + writable: true, + value: newRecord.key + }); + } + } else if (this.keyGenerator !== null && typeof newRecord.key === "number") { + this.keyGenerator.setIfLarger(newRecord.key); + } + const existingRecord = this.records.put(newRecord, noOverwrite); + let rolledBack = false; + const rollbackStoreRecord = () => { + if (rolledBack) { + return; + } + rolledBack = true; + if (existingRecord) { + // overwrite on rollback + this.storeRecord(existingRecord, false); + } else { + // delete on rollback + this.deleteRecord(newRecord.key); + } + }; + rollbackLogForThisOperation.push(rollbackStoreRecord); + if (rollbackLog) { + rollbackLog.push(rollbackStoreRecord); + } + + // Delete existing indexes + if (existingRecord) { + for (const rawIndex of this.rawIndexes.values()) { + rawIndex.records.deleteByValue(newRecord.key); + } + } + + // Update indexes + try { + for (const rawIndex of this.rawIndexes.values()) { + if (rawIndex.initialized) { + rawIndex.storeRecord(newRecord); + } + } + } catch (err) { + // If this request fails here and preventDefault is used to stop the transaction from aborting, we need to roll back the addition of this record to the store, otherwise it will be present in subsequent requests on this transaction. Same for key generator. + if (err.name === "ConstraintError") { + for (const rollback of rollbackLogForThisOperation) { + rollback(); + } + } + throw err; + } + return newRecord.key; + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-deleting-records-from-an-object-store + deleteRecord(key, rollbackLog) { + const deletedRecords = this.records.delete(key); + if (rollbackLog) { + for (const record of deletedRecords) { + rollbackLog.push(() => { + this.storeRecord(record, true); + }); + } + } + for (const rawIndex of this.rawIndexes.values()) { + rawIndex.records.deleteByValue(key); + } + } + + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-clearing-an-object-store + clear(rollbackLog) { + const deletedRecords = this.records.clear(); + if (rollbackLog) { + for (const record of deletedRecords) { + rollbackLog.push(() => { + this.storeRecord(record, true); + }); + } + } + for (const rawIndex of this.rawIndexes.values()) { + rawIndex.records.clear(); + } + } + count(range) { + // optimization: if there is no range, or if the range is everything, then we can just count the total size + if (range === undefined || range.lower === undefined && range.upper === undefined) { + return this.records.size(); + } + let count = 0; + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + for (const record of this.records.values(range)) { + count += 1; + } + return count; + } +} +export default ObjectStore; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/RecordStore.js b/node_modules/fake-indexeddb/build/esm/lib/RecordStore.js new file mode 100644 index 0000000000000000000000000000000000000000..9ec4e4b03fa4a1665dbd35651b0d935fbb8fac7a --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/RecordStore.js @@ -0,0 +1,104 @@ +import FDBKeyRange from "../FDBKeyRange.js"; +import cmp from "./cmp.js"; +import BinarySearchTree from "./binarySearchTree.js"; +class RecordStore { + constructor(keysAreUnique) { + this.keysAreUnique = keysAreUnique; + this.records = new BinarySearchTree(this.keysAreUnique); + } + get(key) { + const range = key instanceof FDBKeyRange ? key : FDBKeyRange.only(key); + return this.records.getRecords(range).next().value; + } + + /** + * Put a new record, and return the overwritten record if an overwrite occurred. + * @param newRecord + * @param noOverwrite - throw a ConstraintError in case of overwrite + */ + put(newRecord, noOverwrite = false) { + return this.records.put(newRecord, noOverwrite); + } + delete(key) { + const range = key instanceof FDBKeyRange ? key : FDBKeyRange.only(key); + const deletedRecords = [...this.records.getRecords(range)]; + for (const record of deletedRecords) { + this.records.delete(record); + } + return deletedRecords; + } + deleteByValue(key) { + const range = key instanceof FDBKeyRange ? key : FDBKeyRange.only(key); + const deletedRecords = []; + for (const record of this.records.getAllRecords()) { + if (range.includes(record.value)) { + this.records.delete(record); + deletedRecords.push(record); + } + } + return deletedRecords; + } + clear() { + const deletedRecords = [...this.records.getAllRecords()]; + this.records = new BinarySearchTree(this.keysAreUnique); + return deletedRecords; + } + values(range, direction = "next") { + const descending = direction === "prev" || direction === "prevunique"; + const records = range ? this.records.getRecords(range, descending) : this.records.getAllRecords(descending); + return { + [Symbol.iterator]: () => { + const next = () => { + return records.next(); + }; + if (direction === "next" || direction === "prev") { + return { + next + }; + } + + // For nextunique/prevunique, return an iterator that skips seen values + // Note that we must return the _lowest_ value regardless of direction: + // > Iterating with "prevunique" visits the same records that "nextunique" + // > visits, but in reverse order. + // https://w3c.github.io/IndexedDB/#dom-idbcursordirection-prevunique + if (direction === "nextunique") { + let previousValue = undefined; + return { + next: () => { + let current = next(); + // for nextunique, continue if we already emitted the lowest unique value + while (!current.done && previousValue !== undefined && cmp(previousValue.key, current.value.key) === 0) { + current = next(); + } + previousValue = current.value; + return current; + } + }; + } + + // prevunique is a bit more complex due to needing to check the next value, which + // invokes the iterable, so we need to keep a buffer of one "lookahead" result + let current = next(); + let nextResult = next(); + return { + next: () => { + while (!nextResult.done && cmp(current.value.key, nextResult.value.key) === 0) { + // note we return the _lowest_ possible value, hence set the current + current = nextResult; + nextResult = next(); + } + const result = current; + current = nextResult; + nextResult = next(); + return result; + } + }; + } + }; + } + size() { + return this.records.size(); + } +} +export default RecordStore; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/binarySearchTree.js b/node_modules/fake-indexeddb/build/esm/lib/binarySearchTree.js new file mode 100644 index 0000000000000000000000000000000000000000..85aa44e5288e71438abff56e8e4209a4d624ffa1 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/binarySearchTree.js @@ -0,0 +1,299 @@ +import FDBKeyRange from "../FDBKeyRange.js"; +import cmp from "./cmp.js"; +import { ConstraintError } from "./errors.js"; +// what fraction of the total number of nodes are allowed to be deleted tombstones? +const MAX_TOMBSTONE_FACTOR = 2 / 3; +const EVERYTHING_KEY_RANGE = new FDBKeyRange(undefined, undefined, false, false); +/** + * Simple red-black binary tree with some aspects of a scapegoat tree. The main goal here is simplicity of + * implementation, tailored to the needs of IndexedDB. + * + * Basically this implements a [red-black tree][1] for insertions, but uses the much simpler [scapegoat tree][2] + * strategy for deletions. Deletions are a simple matter of rebuilding the tree from scratch if more than 2/3 of the + * tree is full of deleted (tombstone) markers. + * + * [1]: https://en.wikipedia.org/wiki/Red%E2%80%93black_tree + * [2]: https://en.wikipedia.org/wiki/Scapegoat_tree + */ +export default class BinarySearchTree { + _numTombstones = 0; + _numNodes = 0; + + /** + * + * @param keysAreUnique - whether keys can be unique, and thus whether we cn skip checking `record.value` when + * comparing. This is basically used to distinguish ObjectStores (where the value is the entire object, not used + * as a key) from non-unique Indexes (where both the key and the value are meaningful keys used for sorting) + */ + constructor(keysAreUnique) { + this._keysAreUnique = !!keysAreUnique; + } + size() { + return this._numNodes - this._numTombstones; + } + get(record) { + return this._getByComparator(this._root, otherRecord => this._compare(record, otherRecord)); + } + contains(record) { + return !!this.get(record); + } + _compare(a, b) { + const keyComparison = cmp(a.key, b.key); + if (keyComparison !== 0) { + return keyComparison; + } + // if keys are unique, then we can (and must) avoid comparing the values, since they may be non-comparable + // (e.g. in the case of an ObjectStore, they are record objects) + return this._keysAreUnique ? 0 : cmp(a.value, b.value); + } + _getByComparator(node, comparator) { + let current = node; + while (current) { + const comparison = comparator(current.record); + if (comparison < 0) { + current = current.left; + } else if (comparison > 0) { + current = current.right; + } else { + return current.record; + } + } + } + + /** + * Put a new record, and return the overwritten record if an overwrite occurred. + * @param record + * @param noOverwrite - throw a ConstraintError in case of overwrite + */ + put(record, noOverwrite = false) { + if (!this._root) { + this._root = { + record, + left: undefined, + right: undefined, + parent: undefined, + deleted: false, + // the root is always black in a red-black tree + red: false + }; + this._numNodes++; + return; + } + return this._put(this._root, record, noOverwrite); + } + _put(node, record, noOverwrite) { + const comparison = this._compare(record, node.record); + if (comparison < 0) { + if (node.left) { + return this._put(node.left, record, noOverwrite); + } else { + node.left = { + record, + left: undefined, + right: undefined, + parent: node, + deleted: false, + red: true + }; + this._onNewNodeInserted(node.left); + } + } else if (comparison > 0) { + if (node.right) { + return this._put(node.right, record, noOverwrite); + } else { + node.right = { + record, + left: undefined, + right: undefined, + parent: node, + deleted: false, + red: true + }; + this._onNewNodeInserted(node.right); + } + } else if (node.deleted) { + // undelete + node.deleted = false; + node.record = record; + this._numTombstones--; + } else if (noOverwrite) { + // replace not allowed in case of noOverwrite + throw new ConstraintError(); + } else { + // replace, don't add, so no need to increment. return the overwritten record + const overwrittenRecord = node.record; + node.record = record; + return overwrittenRecord; + } + } + delete(record) { + if (!this._root) { + return; + } + this._delete(this._root, record); + if (this._numTombstones > this._numNodes * MAX_TOMBSTONE_FACTOR) { + // to keep the implementation simple, and because most users of fake-indexeddb are not going to be deleting + // a lot of nodes, just rebuild the whole tree (defragment) if the tree is too full of tombstones, + // as inspired by the scapegoat tree: https://en.wikipedia.org/wiki/Scapegoat_tree#Deletion + const records = [...this.getAllRecords()]; + this._root = this._rebuild(records, undefined, false); + this._numNodes = records.length; + this._numTombstones = 0; + } + } + _delete(node, record) { + if (!node) { + return; + } + const comparison = this._compare(record, node.record); + if (comparison < 0) { + this._delete(node.left, record); + } else if (comparison > 0) { + this._delete(node.right, record); + } else if (!node.deleted) { + this._numTombstones++; + node.deleted = true; + } + } + *getAllRecords(descending = false) { + yield* this.getRecords(EVERYTHING_KEY_RANGE, descending); + } + *getRecords(keyRange, descending = false) { + yield* this._getRecordsForNode(this._root, keyRange, descending); + } + *_getRecordsForNode(node, keyRange, descending = false) { + if (!node) { + return; + } + yield* this._findRecords(node, keyRange, descending); + } + *_findRecords(node, keyRange, descending = false) { + const { + lower, + upper, + lowerOpen, + upperOpen + } = keyRange; + const { + record: { + key + } + } = node; + const lowerComparison = lower === undefined ? -1 : cmp(lower, key); + const upperComparison = upper === undefined ? 1 : cmp(upper, key); + + // if keys are non-unique then we need to go left/right even for equality + // else we can just do LT/GT rather than LTE/GTE as a slight optimization + const moreLeft = this._keysAreUnique ? lowerComparison < 0 : lowerComparison <= 0; + const moreRight = this._keysAreUnique ? upperComparison > 0 : upperComparison >= 0; + + // in descending mode we start with rightmost nodes, else leftmost + const moreStart = descending ? moreRight : moreLeft; + const moreEnd = descending ? moreLeft : moreRight; + const start = descending ? "right" : "left"; + const end = descending ? "left" : "right"; + + // does the current record actually match the key range? + const lowerMatches = lowerOpen ? lowerComparison < 0 : lowerComparison <= 0; + const upperMatches = upperOpen ? upperComparison > 0 : upperComparison >= 0; + if (moreStart && node[start]) { + yield* this._findRecords(node[start], keyRange, descending); + } + if (lowerMatches && upperMatches && !node.deleted) { + yield node.record; + } + if (moreEnd && node[end]) { + yield* this._findRecords(node[end], keyRange, descending); + } + } + _onNewNodeInserted(newNode) { + this._numNodes++; + this._rebalanceTree(newNode); + } + + // based on https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Insertion + _rebalanceTree(node) { + let parent = node.parent; + do { + // case 1 - no red/black violation + if (!parent.red) { + return; + } + const grandparent = parent.parent; + if (!grandparent) { + // case #4 - parent is the red root, node is also red, so parent goes black + parent.red = false; + return; + } + const parentIsRightChild = parent === grandparent.right; + const uncle = parentIsRightChild ? grandparent.left : grandparent.right; + if (!uncle || !uncle.red) { + if (node === (parentIsRightChild ? parent.left : parent.right)) { + // case #5 - parent is red but uncle is black + this._rotateSubtree(parent, parentIsRightChild); + node = parent; + parent = parentIsRightChild ? grandparent.right : grandparent.left; + } + + // case #6 - node is "outer" grandchild of grandparent + this._rotateSubtree(grandparent, !parentIsRightChild); + parent.red = false; + grandparent.red = true; + return; + } + + // case #2 - parent and uncle are both red, so both of them go black and grandparent goes red + parent.red = false; + uncle.red = false; + grandparent.red = true; + node = grandparent; + } while (node.parent ? parent = node.parent : false); + + // case #3 - current node is the root, all constraints satisfied + } + + // based on https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Implementation + _rotateSubtree(node, right) { + const parent = node.parent; + const newRoot = right ? node.left : node.right; // opposite direction + const newChild = right ? newRoot.right : newRoot.left; + node[right ? "left" : "right"] = newChild; + if (newChild) { + newChild.parent = node; + } + newRoot[right ? "right" : "left"] = node; + newRoot.parent = parent; + node.parent = newRoot; + if (parent) { + parent[node === parent.right ? "right" : "left"] = newRoot; + } else { + this._root = newRoot; + } + return newRoot; + } + + // rebuild the whole tree from scratch, used to avoid too many deletion tombstones accumulating + _rebuild(records, parent, red) { + const { + length + } = records; + if (!length) { + return undefined; + } + const mid = length >>> 1; // like Math.floor(records.length / 2) but fast + + const node = { + record: records[mid], + left: undefined, + right: undefined, + parent, + deleted: false, + red + }; + const left = this._rebuild(records.slice(0, mid), node, !red); + const right = this._rebuild(records.slice(mid + 1), node, !red); + node.left = left; + node.right = right; + return node; + } +} \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/canInjectKey.js b/node_modules/fake-indexeddb/build/esm/lib/canInjectKey.js new file mode 100644 index 0000000000000000000000000000000000000000..609648cfc21ad9b5cd3850aac7b46263c1e82f21 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/canInjectKey.js @@ -0,0 +1,23 @@ +// http://w3c.github.io/IndexedDB/#check-that-a-key-could-be-injected-into-a-value +const canInjectKey = (keyPath, value) => { + if (Array.isArray(keyPath)) { + throw new Error("The key paths used in this section are always strings and never sequences, since it is not possible to create a object store which has a key generator and also has a key path that is a sequence."); + } + const identifiers = keyPath.split("."); + if (identifiers.length === 0) { + throw new Error("Assert: identifiers is not empty"); + } + identifiers.pop(); + for (const identifier of identifiers) { + if (typeof value !== "object" && !Array.isArray(value)) { + return false; + } + const hop = Object.hasOwn(value, identifier); + if (!hop) { + return true; + } + value = value[identifier]; + } + return typeof value === "object" || Array.isArray(value); +}; +export default canInjectKey; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/cloneValueForInsertion.js b/node_modules/fake-indexeddb/build/esm/lib/cloneValueForInsertion.js new file mode 100644 index 0000000000000000000000000000000000000000..37aa4fb4c8062f141743190b208c2d76d0091634 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/cloneValueForInsertion.js @@ -0,0 +1,24 @@ +// https://w3c.github.io/IndexedDB/#clone-value +// Note that we only need to call this during insertions because the spec does not expect any cloning during retrieval, +// only `StructuredDeserialize()` (e.g. see [1]). This is also only required for values, not keys, since keys do not +// require cloning during insertion (e.g. see [2]). +// [1]: https://w3c.github.io/IndexedDB/#retrieve-multiple-items-from-an-object-store +// [2]: https://w3c.github.io/IndexedDB/#add-or-put +export function cloneValueForInsertion(value, transaction) { + // Assert: transaction’s state is active. + if (transaction._state !== "active") { + throw new Error("Assert: transaction state is active"); + } + + // Set transaction’s state to inactive. + transaction._state = "inactive"; + try { + // Let serialized be StructuredSerializeForStorage(value). + // Let clone be ? StructuredDeserialize(serialized, targetRealm). + // Return clone. + return structuredClone(value); + } finally { + // Set transaction’s state to active. + transaction._state = "active"; + } +} \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/closeConnection.js b/node_modules/fake-indexeddb/build/esm/lib/closeConnection.js new file mode 100644 index 0000000000000000000000000000000000000000..ee84040deb6d37538c3ff0df96e5da9be7111084 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/closeConnection.js @@ -0,0 +1,28 @@ +import FakeEvent from "./FakeEvent.js"; +import { queueTask } from "./scheduling.js"; +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#database-closing-steps +const closeConnection = (connection, forced = false) => { + connection._closePending = true; + const transactionsComplete = connection._rawDatabase.transactions.every(transaction => { + return transaction._state === "finished"; + }); + if (transactionsComplete) { + connection._closed = true; + connection._rawDatabase.connections = connection._rawDatabase.connections.filter(otherConnection => { + return connection !== otherConnection; + }); + if (forced) { + const event = new FakeEvent("close", { + bubbles: false, + cancelable: false + }); + event.eventPath = []; + connection.dispatchEvent(event); + } + } else { + queueTask(() => { + closeConnection(connection, forced); + }); + } +}; +export default closeConnection; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/cmp.js b/node_modules/fake-indexeddb/build/esm/lib/cmp.js new file mode 100644 index 0000000000000000000000000000000000000000..86ffe7ca225a765c72f03be409330be5b05fdcdd --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/cmp.js @@ -0,0 +1,77 @@ +import { DataError } from "./errors.js"; +import valueToKey from "./valueToKey.js"; +const getType = x => { + if (typeof x === "number") { + return "Number"; + } + if (Object.prototype.toString.call(x) === "[object Date]") { + return "Date"; + } + if (Array.isArray(x)) { + return "Array"; + } + if (typeof x === "string") { + return "String"; + } + if (x instanceof ArrayBuffer) { + return "Binary"; + } + throw new DataError(); +}; + +// https://w3c.github.io/IndexedDB/#compare-two-keys +const cmp = (first, second) => { + if (second === undefined) { + throw new TypeError(); + } + first = valueToKey(first); + second = valueToKey(second); + const t1 = getType(first); + const t2 = getType(second); + if (t1 !== t2) { + if (t1 === "Array") { + return 1; + } + if (t1 === "Binary" && (t2 === "String" || t2 === "Date" || t2 === "Number")) { + return 1; + } + if (t1 === "String" && (t2 === "Date" || t2 === "Number")) { + return 1; + } + if (t1 === "Date" && t2 === "Number") { + return 1; + } + return -1; + } + if (t1 === "Binary") { + first = new Uint8Array(first); + second = new Uint8Array(second); + } + if (t1 === "Array" || t1 === "Binary") { + const length = Math.min(first.length, second.length); + for (let i = 0; i < length; i++) { + const result = cmp(first[i], second[i]); + if (result !== 0) { + return result; + } + } + if (first.length > second.length) { + return 1; + } + if (first.length < second.length) { + return -1; + } + return 0; + } + if (t1 === "Date") { + if (first.getTime() === second.getTime()) { + return 0; + } + } else { + if (first === second) { + return 0; + } + } + return first > second ? 1 : -1; +}; +export default cmp; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/enforceRange.js b/node_modules/fake-indexeddb/build/esm/lib/enforceRange.js new file mode 100644 index 0000000000000000000000000000000000000000..7ad148a166965dab509e58697f98be4aeb5b9286 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/enforceRange.js @@ -0,0 +1,13 @@ +// https://heycam.github.io/webidl/#EnforceRange + +const enforceRange = (num, type) => { + const min = 0; + const max = type === "unsigned long" ? 4294967295 : 9007199254740991; + if (isNaN(num) || num < min || num > max) { + throw new TypeError(); + } + if (num >= 0) { + return Math.floor(num); + } +}; +export default enforceRange; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/errors.js b/node_modules/fake-indexeddb/build/esm/lib/errors.js new file mode 100644 index 0000000000000000000000000000000000000000..95a3784acbaaa773ee4a560fd88d096d67aafa57 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/errors.js @@ -0,0 +1,83 @@ +const messages = { + AbortError: "A request was aborted, for example through a call to IDBTransaction.abort.", + ConstraintError: "A mutation operation in the transaction failed because a constraint was not satisfied. For example, an object such as an object store or index already exists and a request attempted to create a new one.", + DataCloneError: "The data being stored could not be cloned by the internal structured cloning algorithm.", + DataError: "Data provided to an operation does not meet requirements.", + InvalidAccessError: "An invalid operation was performed on an object. For example transaction creation attempt was made, but an empty scope was provided.", + InvalidStateError: "An operation was called on an object on which it is not allowed or at a time when it is not allowed. Also occurs if a request is made on a source object that has been deleted or removed. Use TransactionInactiveError or ReadOnlyError when possible, as they are more specific variations of InvalidStateError.", + NotFoundError: "The operation failed because the requested database object could not be found. For example, an object store did not exist but was being opened.", + ReadOnlyError: 'The mutating operation was attempted in a "readonly" transaction.', + TransactionInactiveError: "A request was placed against a transaction which is currently not active, or which is finished.", + SyntaxError: "The keypath argument contains an invalid key path", + VersionError: "An attempt was made to open a database using a lower version than the existing version." +}; + +// Cannot set an error code on an error using the normal setter; +// this leads to "Cannot set property code of which has only a getter" +const setErrorCode = (error, value) => { + Object.defineProperty(error, 'code', { + value, + writable: false, + enumerable: true, + configurable: false + }); +}; +export class AbortError extends DOMException { + constructor(message = messages.AbortError) { + super(message, "AbortError"); + } +} +export class ConstraintError extends DOMException { + constructor(message = messages.ConstraintError) { + super(message, "ConstraintError"); + } +} +export class DataCloneError extends DOMException { + constructor(message = messages.DataCloneError) { + super(message, "DataCloneError"); + } +} +export class DataError extends DOMException { + constructor(message = messages.DataError) { + super(message, "DataError"); + setErrorCode(this, 0); + } +} +export class InvalidAccessError extends DOMException { + constructor(message = messages.InvalidAccessError) { + super(message, "InvalidAccessError"); + } +} +export class InvalidStateError extends DOMException { + constructor(message = messages.InvalidStateError) { + super(message, "InvalidStateError"); + setErrorCode(this, 11); + } +} +export class NotFoundError extends DOMException { + constructor(message = messages.NotFoundError) { + super(message, "NotFoundError"); + } +} +export class ReadOnlyError extends DOMException { + constructor(message = messages.ReadOnlyError) { + super(message, "ReadOnlyError"); + } +} +export class SyntaxError extends DOMException { + constructor(message = messages.VersionError) { + super(message, "SyntaxError"); + setErrorCode(this, 12); + } +} +export class TransactionInactiveError extends DOMException { + constructor(message = messages.TransactionInactiveError) { + super(message, "TransactionInactiveError"); + setErrorCode(this, 0); + } +} +export class VersionError extends DOMException { + constructor(message = messages.VersionError) { + super(message, "VersionError"); + } +} \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/extractGetAllOptions.js b/node_modules/fake-indexeddb/build/esm/lib/extractGetAllOptions.js new file mode 100644 index 0000000000000000000000000000000000000000..435e83834ebf364c899aa1245709cd46aeea667a --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/extractGetAllOptions.js @@ -0,0 +1,32 @@ +import isPotentiallyValidKeyRange from "./isPotentiallyValidKeyRange.js"; +import enforceRange from "./enforceRange.js"; +// https://www.w3.org/TR/IndexedDB/#create-request-to-retrieve-multiple-items +const extractGetAllOptions = (queryOrOptions, count, numArguments) => { + let query; + let direction; + if (queryOrOptions === undefined || queryOrOptions === null || isPotentiallyValidKeyRange(queryOrOptions)) { + // queryOrOptions is FDBKeyRange | Key | null | undefined + query = queryOrOptions; + if (numArguments > 1 && count !== undefined) { + count = enforceRange(count, "unsigned long"); + } + } else { + // queryOrOptions is FDBGetAllOptions + const getAllOptions = queryOrOptions; + if (getAllOptions.query !== undefined) { + query = getAllOptions.query; + } + if (getAllOptions.count !== undefined) { + count = enforceRange(getAllOptions.count, "unsigned long"); + } + if (getAllOptions.direction !== undefined) { + direction = getAllOptions.direction; + } + } + return { + query, + count, + direction + }; +}; +export default extractGetAllOptions; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/extractKey.js b/node_modules/fake-indexeddb/build/esm/lib/extractKey.js new file mode 100644 index 0000000000000000000000000000000000000000..eca675820698c670c42786016ffdf952b55b92c0 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/extractKey.js @@ -0,0 +1,53 @@ +import valueToKey from "./valueToKey.js"; +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-extracting-a-key-from-a-value-using-a-key-path +const extractKey = (keyPath, value) => { + if (Array.isArray(keyPath)) { + const result = []; + for (let item of keyPath) { + // This doesn't make sense to me based on the spec, but it is needed to pass the W3C KeyPath tests (see same + // comment in validateKeyPath) + if (item !== undefined && item !== null && typeof item !== "string" && item.toString) { + item = item.toString(); + } + const key = extractKey(item, value).key; + result.push(valueToKey(key)); + } + return { + type: "found", + key: result + }; + } + if (keyPath === "") { + return { + type: "found", + key: value + }; + } + let remainingKeyPath = keyPath; + let object = value; + while (remainingKeyPath !== null) { + let identifier; + const i = remainingKeyPath.indexOf("."); + if (i >= 0) { + identifier = remainingKeyPath.slice(0, i); + remainingKeyPath = remainingKeyPath.slice(i + 1); + } else { + identifier = remainingKeyPath; + remainingKeyPath = null; + } + + // special cases: https://w3c.github.io/IndexedDB/#evaluate-a-key-path-on-a-value + const isSpecialIdentifier = identifier === "length" && (typeof object === "string" || Array.isArray(object)) || (identifier === "size" || identifier === "type") && typeof Blob !== "undefined" && object instanceof Blob || (identifier === "name" || identifier === "lastModified") && typeof File !== "undefined" && object instanceof File; + if (!isSpecialIdentifier && (typeof object !== "object" || object === null || !Object.hasOwn(object, identifier))) { + return { + type: "notFound" + }; + } + object = object[identifier]; + } + return { + type: "found", + key: object + }; +}; +export default extractKey; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/getKeyPath.js b/node_modules/fake-indexeddb/build/esm/lib/getKeyPath.js new file mode 100644 index 0000000000000000000000000000000000000000..d1c88f9ab4e7d4cf754297e66fda47df5deed6af --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/getKeyPath.js @@ -0,0 +1,10 @@ +// Keys provided as functions or arrays or objects need to be stringified +const convertKey = key => typeof key === 'object' && key ? key + '' : key; + +// https://www.w3.org/TR/IndexedDB/#dom-idbobjectstore-keypath +export function getKeyPath(keyPath) { + // It's important to clone the Array here because of the WPT test: + // "Different instances are returned from different store instances." + // Also note that the same instance must be returned across multiple gets + return Array.isArray(keyPath) ? keyPath.map(convertKey) : convertKey(keyPath); +} \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/intersection.js b/node_modules/fake-indexeddb/build/esm/lib/intersection.js new file mode 100644 index 0000000000000000000000000000000000000000..1430f6704eb693210a5d76bed421cde8a0960e2b --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/intersection.js @@ -0,0 +1,12 @@ +/** + * Minimal polyfill of `Set.prototype.intersection`, available in Node 22+. + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/intersection + * @param set1 + * @param set2 + */ +export function intersection(set1, set2) { + if ("intersection" in set1) { + return set1.intersection(set2); + } + return new Set([...set1].filter(item => set2.has(item))); +} \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/isPotentiallyValidKeyRange.js b/node_modules/fake-indexeddb/build/esm/lib/isPotentiallyValidKeyRange.js new file mode 100644 index 0000000000000000000000000000000000000000..caf9ba1542e2ac70fd4e3c4e6af64f39a7dfa528 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/isPotentiallyValidKeyRange.js @@ -0,0 +1,18 @@ +import FDBKeyRange from "../FDBKeyRange.js"; +import valueToKeyWithoutThrowing, { INVALID_TYPE } from "./valueToKeyWithoutThrowing.js"; + +// https://www.w3.org/TR/IndexedDB/#is-a-potentially-valid-key-range +const isPotentiallyValidKeyRange = value => { + // If value is a key range, return true. + if (value instanceof FDBKeyRange) { + return true; + } + + // Let key be the result of converting a value to a key with value. + const key = valueToKeyWithoutThrowing(value); + + // If key is "invalid type" return false. + // Else return true. + return key !== INVALID_TYPE; +}; +export default isPotentiallyValidKeyRange; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/isSharedArrayBuffer.js b/node_modules/fake-indexeddb/build/esm/lib/isSharedArrayBuffer.js new file mode 100644 index 0000000000000000000000000000000000000000..3f04fbe6212c520d2be608ca7647d6a7acf5445a --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/isSharedArrayBuffer.js @@ -0,0 +1,3 @@ +export default function isSharedArrayBuffer(input) { + return typeof SharedArrayBuffer !== "undefined" && input instanceof SharedArrayBuffer; +} \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/scheduling.js b/node_modules/fake-indexeddb/build/esm/lib/scheduling.js new file mode 100644 index 0000000000000000000000000000000000000000..ed18e601701af1ac4054576226043dc99960a8cb --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/scheduling.js @@ -0,0 +1,39 @@ +// When running within Node.js (including jsdom), we want to use setImmediate +// (which runs immediately) rather than setTimeout (which enforces a minimum +// delay of 1ms, and on Windows only has a resolution of 15ms or so). jsdom +// doesn't provide setImmediate (to better match the browser environment) and +// sandboxes scripts, but its sandbox is by necessity imperfect, so we can break +// out of it: +// +// - https://github.com/jsdom/jsdom#executing-scripts +// - https://github.com/jsdom/jsdom/issues/2729 +// - https://github.com/scala-js/scala-js-macrotask-executor/pull/17 +function getSetImmediateFromJsdom() { + if (typeof navigator !== "undefined" && /jsdom/.test(navigator.userAgent)) { + const outerRealmFunctionConstructor = Node.constructor; + return new outerRealmFunctionConstructor("return setImmediate")(); + } else { + return undefined; + } +} + +// waiting on this PR for typescript types: https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1249 + +// 'postTask' runs right after microtasks, so equivalent to setTimeout but without the 4ms clamping. +// Using the default priority of 'user-visible' to avoid blocking input while still running fairly quickly. +// See: https://developer.mozilla.org/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#task_priorities +const schedulerPostTask = typeof scheduler !== "undefined" && (fn => scheduler.postTask(fn)); + +// fallback for environments that don't support any of the above +const doSetTimeout = fn => setTimeout(fn, 0); + +// Schedules a task to run later. Use Node.js's setImmediate if available and +// setTimeout otherwise. Note that options like process.nextTick or +// queueMicrotask will likely not work: IndexedDB semantics require that +// transactions are marked as not active when the event loop runs. The next +// tick queue and microtask queue run within the current event loop macrotask, +// so they'd process database operations too quickly. +export const queueTask = fn => { + const setImmediate = globalThis.setImmediate || getSetImmediateFromJsdom() || schedulerPostTask || doSetTimeout; + setImmediate(fn); +}; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/types.js b/node_modules/fake-indexeddb/build/esm/lib/types.js new file mode 100644 index 0000000000000000000000000000000000000000..8cec2e9ced0d3575a0f7b97c7396d5bcefe0ea5e --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/types.js @@ -0,0 +1 @@ +export {}; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/validateKeyPath.js b/node_modules/fake-indexeddb/build/esm/lib/validateKeyPath.js new file mode 100644 index 0000000000000000000000000000000000000000..b64defe82344163d51f58f1d1544cdeabfc42aea --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/validateKeyPath.js @@ -0,0 +1,47 @@ +import { SyntaxError } from "./errors.js"; +// http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-valid-key-path +const validateKeyPath = (keyPath, parent) => { + // This doesn't make sense to me based on the spec, but it is needed to pass the W3C KeyPath tests (see same + // comment in extractKey) + if (keyPath !== undefined && keyPath !== null && typeof keyPath !== "string" && keyPath.toString && (parent === "array" || !Array.isArray(keyPath))) { + keyPath = keyPath.toString(); + } + if (typeof keyPath === "string") { + if (keyPath === "" && parent !== "string") { + return; + } + try { + // https://mathiasbynens.be/demo/javascript-identifier-regex for ECMAScript 5.1 / Unicode v7.0.0, with + // reserved words at beginning removed + const validIdentifierRegex = + // eslint-disable-next-line no-misleading-character-class + /^(?:[$A-Z_a-z\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\u08A0-\u08B2\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\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\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\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\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-\u13F4\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-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\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-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\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-\uAB5F\uAB64\uAB65\uABC0-\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])(?:[$0-9A-Z_a-z\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\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\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E\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\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-\u13F4\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\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\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\u200C\u200D\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-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\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-\uAB5F\uAB64\uAB65\uABC0-\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-\uFE2D\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])*$/; + if (keyPath.length >= 1 && validIdentifierRegex.test(keyPath)) { + return; + } + } catch (err) { + throw new SyntaxError(err.message); + } + if (keyPath.indexOf(" ") >= 0) { + throw new SyntaxError("The keypath argument contains an invalid key path (no spaces allowed)."); + } + } + if (Array.isArray(keyPath) && keyPath.length > 0) { + if (parent) { + // No nested arrays + throw new SyntaxError("The keypath argument contains an invalid key path (nested arrays)."); + } + for (const part of keyPath) { + validateKeyPath(part, "array"); + } + return; + } else if (typeof keyPath === "string" && keyPath.indexOf(".") >= 0) { + keyPath = keyPath.split("."); + for (const part of keyPath) { + validateKeyPath(part, "string"); + } + return; + } + throw new SyntaxError(); +}; +export default validateKeyPath; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/validateRequiredArguments.js b/node_modules/fake-indexeddb/build/esm/lib/validateRequiredArguments.js new file mode 100644 index 0000000000000000000000000000000000000000..e7aecb1f97c15f8fdbd8745911bb2c6a69820065 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/validateRequiredArguments.js @@ -0,0 +1,7 @@ +// WebIDL requires passing the right number of non-optional arguments, e.g. IDBFactory.open() must have at least 1 arg +export function validateRequiredArguments(numArguments, expectedNumArguments, methodName) { + if (numArguments < expectedNumArguments) { + // imitate Firefox's error message + throw new TypeError(`${methodName}: At least ${expectedNumArguments} ${expectedNumArguments === 1 ? "argument" : "arguments"} ` + `required, but only ${arguments.length} passed`); + } +} \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/valueToKey.js b/node_modules/fake-indexeddb/build/esm/lib/valueToKey.js new file mode 100644 index 0000000000000000000000000000000000000000..1be3fe2be451b9250a3b4a03b3cc6ab08599978d --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/valueToKey.js @@ -0,0 +1,14 @@ +import { DataError } from "./errors.js"; +import valueToKeyWithoutThrowing, { INVALID_TYPE, INVALID_VALUE } from "./valueToKeyWithoutThrowing.js"; +// https://w3c.github.io/IndexedDB/#convert-value-to-key +// Plus throwing a DataError for invalid value/invalid key, which is commonly done +// in lots of IndexedDB operations +const valueToKey = (input, seen) => { + const result = valueToKeyWithoutThrowing(input, seen); + if (result === INVALID_VALUE || result === INVALID_TYPE) { + // If key is "invalid value" or "invalid type", throw a "DataError" DOMException + throw new DataError(); + } + return result; +}; +export default valueToKey; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/valueToKeyRange.js b/node_modules/fake-indexeddb/build/esm/lib/valueToKeyRange.js new file mode 100644 index 0000000000000000000000000000000000000000..ff768ca09ef0944378fdae949160858b2d4693d3 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/valueToKeyRange.js @@ -0,0 +1,19 @@ +import FDBKeyRange from "../FDBKeyRange.js"; +import { DataError } from "./errors.js"; +import valueToKey from "./valueToKey.js"; + +// http://w3c.github.io/IndexedDB/#convert-a-value-to-a-key-range +const valueToKeyRange = (value, nullDisallowedFlag = false) => { + if (value instanceof FDBKeyRange) { + return value; + } + if (value === null || value === undefined) { + if (nullDisallowedFlag) { + throw new DataError(); + } + return new FDBKeyRange(undefined, undefined, false, false); + } + const key = valueToKey(value); + return FDBKeyRange.only(key); +}; +export default valueToKeyRange; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/build/esm/lib/valueToKeyWithoutThrowing.js b/node_modules/fake-indexeddb/build/esm/lib/valueToKeyWithoutThrowing.js new file mode 100644 index 0000000000000000000000000000000000000000..f3ae5c94bec26d841a22bbd129cc1362da2e4918 --- /dev/null +++ b/node_modules/fake-indexeddb/build/esm/lib/valueToKeyWithoutThrowing.js @@ -0,0 +1,95 @@ +import isSharedArrayBuffer from "./isSharedArrayBuffer.js"; +export const INVALID_TYPE = Symbol("INVALID_TYPE"); +export const INVALID_VALUE = Symbol("INVALID_VALUE"); + +// https://w3c.github.io/IndexedDB/#convert-value-to-key +// The "without exceptions" version is because we typically want to throw exceptions (DataError) but not for +// the "is potentially valid key range" routine. +const valueToKeyWithoutThrowing = (input, seen) => { + if (typeof input === "number") { + if (isNaN(input)) { + // If input is NaN then return "invalid value". + return INVALID_VALUE; + } + return input; + } else if (Object.prototype.toString.call(input) === "[object Date]") { + const ms = input.valueOf(); + if (isNaN(ms)) { + // If ms is NaN then return "invalid value". + return INVALID_VALUE; + } + return new Date(ms); + } else if (typeof input === "string") { + return input; + } else if ( + // https://w3c.github.io/IndexedDB/#ref-for-dfn-buffer-source-type + input instanceof ArrayBuffer || isSharedArrayBuffer(input) || typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView && ArrayBuffer.isView(input)) { + // We can't consistently test detachedness, so instead we check if byteLength === 0 + // This isn't foolproof, but there's no perfect way to detect if Uint8Arrays or + // SharedArrayBuffers are detached + if ("detached" in input ? input.detached : input.byteLength === 0) { + // If input is detached then return "invalid value". + return INVALID_VALUE; + } + let arrayBuffer; + let offset = 0; + let length = 0; + if (input instanceof ArrayBuffer || isSharedArrayBuffer(input)) { + arrayBuffer = input; + length = input.byteLength; + } else { + arrayBuffer = input.buffer; + offset = input.byteOffset; + length = input.byteLength; + } + return arrayBuffer.slice(offset, offset + length); + } else if (Array.isArray(input)) { + if (seen === undefined) { + seen = new Set(); + } else if (seen.has(input)) { + // If seen contains input, then return "invalid value". + return INVALID_VALUE; + } + seen.add(input); + + // This algorithm is tricky to account for `bindings-inject-keys-bypass.any.js`. We _should_ return early when + // encountering an invalid key/type, but we also need to avoid triggering `Object.prototype['10']` if it's been + // overridden. One simple way to do this (and which doesn't rely on sparse arrays or other exotic solutions that + // could cause de-opts) is to use `Array.from()` with a mapper function, which does not trigger the prototype + // setter [1]. It does prevent an early return, but we can at least short-circuit inside the mapper function + // (which isn't strictly necessary to pass the WPTs, but is closer to the spec). + // [1]: See https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.from, specifically + // the chain CreateDataPropertyOrThrow -> CreateDataProperty -> DefineOwnProperty which defines + // the array element as an "own" property. + let hasInvalid = false; + const keys = Array.from({ + length: input.length + }, (_, i) => { + if (hasInvalid) { + return; + } + const hop = Object.hasOwn(input, i); + if (!hop) { + // If hop is false, return "invalid value". + hasInvalid = true; + return; + } + const entry = input[i]; + const key = valueToKeyWithoutThrowing(entry, seen); + // If key is "invalid value" or "invalid type" abort these steps and return "invalid value". + if (key === INVALID_VALUE || key === INVALID_TYPE) { + hasInvalid = true; + return; + } + return key; + }); + if (hasInvalid) { + return INVALID_VALUE; + } + return keys; + } else { + // Otherwise: Return "invalid type". + return INVALID_TYPE; + } +}; +export default valueToKeyWithoutThrowing; \ No newline at end of file diff --git a/node_modules/fake-indexeddb/lib/FDBCursor.d.ts b/node_modules/fake-indexeddb/lib/FDBCursor.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6e6cab8a5b5463194f3fe1fd0695fcfc73e7559b --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBCursor.d.ts @@ -0,0 +1,2 @@ +declare const FDBCursor: typeof IDBCursor; +export default FDBCursor; diff --git a/node_modules/fake-indexeddb/lib/FDBCursor.js b/node_modules/fake-indexeddb/lib/FDBCursor.js new file mode 100644 index 0000000000000000000000000000000000000000..3230557aef0836963144b56877afaf011cec9dd6 --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBCursor.js @@ -0,0 +1 @@ +module.exports = require("../build/cjs/FDBCursor"); diff --git a/node_modules/fake-indexeddb/lib/FDBCursorWithValue.d.ts b/node_modules/fake-indexeddb/lib/FDBCursorWithValue.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..75167ca375d80f8d1865c0d1ddd3a31911a02407 --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBCursorWithValue.d.ts @@ -0,0 +1,2 @@ +declare const FDBCursorWithValue: typeof IDBCursorWithValue; +export default FDBCursorWithValue; diff --git a/node_modules/fake-indexeddb/lib/FDBCursorWithValue.js b/node_modules/fake-indexeddb/lib/FDBCursorWithValue.js new file mode 100644 index 0000000000000000000000000000000000000000..afeadd8ec1e34ce1e0eac633ced2c38485a7c8b3 --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBCursorWithValue.js @@ -0,0 +1 @@ +module.exports = require("../build/cjs/FDBCursorWithValue"); diff --git a/node_modules/fake-indexeddb/lib/FDBDatabase.d.ts b/node_modules/fake-indexeddb/lib/FDBDatabase.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ac33247cfcf859d4f798e0b4e619d1f7fb0be503 --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBDatabase.d.ts @@ -0,0 +1,2 @@ +declare const FDBDatabase: typeof IDBDatabase; +export default FDBDatabase; diff --git a/node_modules/fake-indexeddb/lib/FDBDatabase.js b/node_modules/fake-indexeddb/lib/FDBDatabase.js new file mode 100644 index 0000000000000000000000000000000000000000..210d86dd10c420733adc88f8f01aa2d70d7a360f --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBDatabase.js @@ -0,0 +1 @@ +module.exports = require("../build/cjs/FDBDatabase"); diff --git a/node_modules/fake-indexeddb/lib/FDBFactory.d.ts b/node_modules/fake-indexeddb/lib/FDBFactory.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e124098972349823ecd5d44e45f5aed460a67da2 --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBFactory.d.ts @@ -0,0 +1,2 @@ +declare const FDBFactory: typeof IDBFactory; +export default FDBFactory; diff --git a/node_modules/fake-indexeddb/lib/FDBFactory.js b/node_modules/fake-indexeddb/lib/FDBFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..a64dcaa94594748ab3f07b1b26b15683c5592529 --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBFactory.js @@ -0,0 +1 @@ +module.exports = require("../build/cjs/FDBFactory"); diff --git a/node_modules/fake-indexeddb/lib/FDBIndex.d.ts b/node_modules/fake-indexeddb/lib/FDBIndex.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b12adb51af6e573c481336eef6f34f91d5a021c7 --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBIndex.d.ts @@ -0,0 +1,2 @@ +declare const FDBIndex: typeof IDBIndex; +export default FDBIndex; diff --git a/node_modules/fake-indexeddb/lib/FDBIndex.js b/node_modules/fake-indexeddb/lib/FDBIndex.js new file mode 100644 index 0000000000000000000000000000000000000000..b545a0da06b41f1ab0d1fef81b4fa24b88ed9e3c --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBIndex.js @@ -0,0 +1 @@ +module.exports = require("../build/cjs/FDBIndex"); diff --git a/node_modules/fake-indexeddb/lib/FDBKeyRange.d.ts b/node_modules/fake-indexeddb/lib/FDBKeyRange.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ef649952081c957a25024ab94c98fd52dc146022 --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBKeyRange.d.ts @@ -0,0 +1,2 @@ +declare const FDBKeyRange: typeof IDBKeyRange; +export default FDBKeyRange; diff --git a/node_modules/fake-indexeddb/lib/FDBKeyRange.js b/node_modules/fake-indexeddb/lib/FDBKeyRange.js new file mode 100644 index 0000000000000000000000000000000000000000..4fb454aa30c579ba4bf1a6b0fb78d5358403f102 --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBKeyRange.js @@ -0,0 +1 @@ +module.exports = require("../build/cjs/FDBKeyRange"); diff --git a/node_modules/fake-indexeddb/lib/FDBObjectStore.d.ts b/node_modules/fake-indexeddb/lib/FDBObjectStore.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0fff3fc4d1b50ab9f793bbeecefe388f7e00c5f3 --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBObjectStore.d.ts @@ -0,0 +1,2 @@ +declare const FDBObjectStore: typeof IDBObjectStore; +export default FDBObjectStore; diff --git a/node_modules/fake-indexeddb/lib/FDBObjectStore.js b/node_modules/fake-indexeddb/lib/FDBObjectStore.js new file mode 100644 index 0000000000000000000000000000000000000000..0068e296909f136367cac69821adabf7d312dc06 --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBObjectStore.js @@ -0,0 +1 @@ +module.exports = require("../build/cjs/FDBObjectStore"); diff --git a/node_modules/fake-indexeddb/lib/FDBOpenDBRequest.d.ts b/node_modules/fake-indexeddb/lib/FDBOpenDBRequest.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f7415b45ae3229d66c10aae39e749d7405cc06f4 --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBOpenDBRequest.d.ts @@ -0,0 +1,2 @@ +declare const FDBOpenDBRequest: typeof IDBOpenDBRequest; +export default FDBOpenDBRequest; diff --git a/node_modules/fake-indexeddb/lib/FDBOpenDBRequest.js b/node_modules/fake-indexeddb/lib/FDBOpenDBRequest.js new file mode 100644 index 0000000000000000000000000000000000000000..2e043f07d9e97e1c32c61b62168a6737d3b91cec --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBOpenDBRequest.js @@ -0,0 +1 @@ +module.exports = require("../build/cjs/FDBOpenDBRequest"); diff --git a/node_modules/fake-indexeddb/lib/FDBRequest.d.ts b/node_modules/fake-indexeddb/lib/FDBRequest.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..04def7312cb3062d5926eeb445bfbb4a28497de8 --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBRequest.d.ts @@ -0,0 +1,2 @@ +declare const FDBRequest: typeof IDBRequest; +export default FDBRequest; diff --git a/node_modules/fake-indexeddb/lib/FDBRequest.js b/node_modules/fake-indexeddb/lib/FDBRequest.js new file mode 100644 index 0000000000000000000000000000000000000000..6b32ac5167be46d3ba1452233b193d0805619dc0 --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBRequest.js @@ -0,0 +1 @@ +module.exports = require("../build/cjs/FDBRequest"); diff --git a/node_modules/fake-indexeddb/lib/FDBTransaction.d.ts b/node_modules/fake-indexeddb/lib/FDBTransaction.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9d5e58bf11beaa1a404d11ec715b11070116ab99 --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBTransaction.d.ts @@ -0,0 +1,2 @@ +declare const FDBTransaction: typeof IDBTransaction; +export default FDBTransaction; diff --git a/node_modules/fake-indexeddb/lib/FDBTransaction.js b/node_modules/fake-indexeddb/lib/FDBTransaction.js new file mode 100644 index 0000000000000000000000000000000000000000..0364ce501f520dc8ad95bfda1bbcae677af517dc --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBTransaction.js @@ -0,0 +1 @@ +module.exports = require("../build/cjs/FDBTransaction"); diff --git a/node_modules/fake-indexeddb/lib/FDBVersionChangeEvent.d.ts b/node_modules/fake-indexeddb/lib/FDBVersionChangeEvent.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d5113176e193da7fa8cf1f260e9105584d86054d --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBVersionChangeEvent.d.ts @@ -0,0 +1,2 @@ +declare const FDBVersionChangeEvent: typeof IDBVersionChangeEvent; +export default FDBVersionChangeEvent; diff --git a/node_modules/fake-indexeddb/lib/FDBVersionChangeEvent.js b/node_modules/fake-indexeddb/lib/FDBVersionChangeEvent.js new file mode 100644 index 0000000000000000000000000000000000000000..413db77142758b7f771bbe6fcc57914c76aa8248 --- /dev/null +++ b/node_modules/fake-indexeddb/lib/FDBVersionChangeEvent.js @@ -0,0 +1 @@ +module.exports = require("../build/cjs/FDBVersionChangeEvent");